SwiftUI

N 人看过

ESE 提示可用的修饰

网站资源

点击这个 调色网站

点击这个 图像尺寸变更

点击这个 图标设计:(选择1024x1024像素)

点击这个阿里巴巴图标库

SwiftUI内置控件

布局

HStack(alignment: .leading对齐方式,spacing:10该stack中控件之间的距离) 水平摆放
VStack 竖直摆放
ZStack 叠加摆放
Group 多屏幕展示(多在预览时使用,支持frame)

列表

List(与ForEach用法相同,ForEach放在List里)

数组是继承Identifiable
List(0..<5可放置数组)){ i in
} 列表
如果没有继承Identifiable的话,需要手动写id
List(数组.identified(by:.id)) {}
简单数组就可以用自身作为id
List([1,2,3].identified(by:.self)){}

ScrollView 可滑动的列表,一般放在NavigitionView内

NavigationLink(destination:跳转后的页面){ } 点击可跳转,写在NavigitionView里

//Navigition头部分,修饰写在NavigitionView里面
.navigationBarTitle(Text(""),displayMode:.inline)字体的大小
.navigationBarItems(trailing: Image( ))//可以放另一视图

Form{
Section(header: 小节题目内容){
//小节内的内容
}
Section(header: 小节题目内容){
//小节内的内容
}
}

文字、图片

Text(“”)

TextField(“”, text: $name) //@State private var name = “”

修饰

.keyboardType() 弹出键盘类型
.numberPad和.decimalPad 两种键盘类型

SecureField

Image(system name: “ SF中的图标名称”)

修饰语句:

.font( ) 字体样式
.font(,system(size: )) 自定义字体大小
.frame(width: ,height: ) 尺寸
.foregroundColor(color: ) 颜色
.offset(x: ,y: ) 偏移量(UIScreen.main.bounds.height屏幕的高度)
.toggle( ) 在真假之间转换
.imageScale(.large) 调整图片大小
.aspectRatio(contentMode: .fit) 图片大小自适应屏幕,.fill是占满屏幕
.frame(minWidth: 0,maxWidth: .infinith) 图片最小宽度为0,最大为无穷
.cornerRadius( ) 圆角
.clipShape(Circle()形状) 裁剪
.overlay(Circle().stroke(Color.black, llineWidth: 5)描边的线) 覆盖的图案
.shadow(radius: ) 阴影
.tapAction{
点击后实现的代码,回调函数
} 轻触手势

动画类

单个的动画(俩种同时都有时,单个动画优先展示)

.transitiooon(.move(edge: .trailing)) 从边缘滑出
.rotationEffect 旋转
.rotation3DEffect(Angle(degrees: ), axis: (x: , y: , z: ))3D旋转
.animation(.spring()) 反弹动画
.animation(.basic(duration: 动画时间, curve: .easeInoOut)) 延迟动画

统一的动画

withAnimation(.basic基本动画(duration: 1动画时间)){
这里的值发生改变时,所有包含这个值的视图都加上了动画
}

按钮

Button(action: {
//点击后实现的代码
}) {
//按钮样式
}

EditButton() 启用或禁用列表中项目的编辑模式
Toggle(isOn: $布尔值) {
Text(“ “)
} 开关按钮

提示框

Alert

struct test: View {
    @State private var editing = false
    var body: some View {
        Button(action: {
            self.editing = true
        }){
            Text("show it")
        }
        .alert(isPresented: $editing){
        Alert(title: Text("alert"), message: Text("easy"),  primaryButton: .default(Text("yes") ,action: {
                print("点了yes欧")
                }),  secondaryButton: .destructive(Text("no")))
        }
    }
}

Modal
Popovers

struct test: View {
    @State private var editing = false
    var body: some View {
        Button("show it"){
            self.editing = true
        }.popover(isPresented: self.$editing, arrowEdge: .bottom) {
            Text("hello, this is a new world")
        }
    }
}

Sheet(和Popovers一模一样)

struct test: View {
    @State private var showingSheet = false
    var body: some View {
        Button("Show Sheet") {
            self.showingSheet.toggle()
        }
        .sheet(isPresented: $showingSheet) {
            Text("6")//也可以写成一个页面
        }
    }
}

ActionSheet

struct test: View {
    @State private var editing = false
    var body: some View {
        Button(action: {
            self.editing = true
        }){
            Text("show it")
        }
        .actionSheet(isPresented: $editing) {
            ActionSheet(title: Text("确定吗?"), message: Text("此操作会。。。"), buttons: [.destructive(Text("确定")), .cancel(Text("撤销"))])
        }
    }
}

选择器

DatePicker(“选择器的标题”,selection: 选择器的值, displayedComponents: ) 时间选择器

displayedComponents用来决定用户应该看到哪种选项:

默认为月-日-星期-小时-分钟
.date 显示年-月-日
.hourAndMinute 显示小时-分钟

Picker(“”,selection: ) 选择器

.pickerStyle(SegmentedPickerStyle( )) 另一种风格的选择器
单个选择滚轮

struct test: View {
    var choice = ["food","medicine","cosmetics"]
    @State private var index = 0
    var body: some View {
        Picker(selection: $index, label: Text("choose")) {
            ForEach (0..<choice.count) { i in
                Text(self.choice[i])
            }
        }
    }
}

多个选择滚轮

struct test: View {

    @State var data: [(String, [String])] = [
        ("One", Array(0...5).map { "\($0)" }),
        ("Two", Array(0...36).map { "\($0)" }),
        ("Three", Array(0...365).map { "\($0)" })
    ]
    @State var selection: [String] = [0, 0, 21].map { "\($0)" }

    var body: some View {
        VStack{
            Text(verbatim: "Selection: \(selection)")
            MultiPicker(data: data, selection: $selection)
            .frame(height: 300)
        }
    }

}
struct MultiPicker: View  {

    typealias Label = String
    typealias Entry = String

    let data: [ (Label, [Entry]) ]
    @Binding var selection: [Entry]

    var body: some View {
        GeometryReader { geometry in
            HStack {
                ForEach(0..<self.data.count) { column in
                    Picker(self.data[column].0, selection: self.$selection[column]) {
                        ForEach(0..<self.data[column].1.count) { row in
                            Text(verbatim: self.data[column].1[row])
                            .tag(self.data[column].1[row])
                        }
                    }
                    .pickerStyle(WheelPickerStyle())
                    .frame(width: geometry.size.width / CGFloat(self.data.count), height: geometry.size.height)
                    .clipped()
                }
            }
        }
    }
}

cornerRadius shadow foregroundColor background frame 都可以修饰选择器
.pickerStyle(SegmentedPickerStyle()) 可以把滚轮换成按钮
按钮也可以是图片

图案形状

Circle 圆形
Edge
Rectangle 好看的小方块
Path
RoundedRectangle

GeometryReader { geometry in
Text(“hello”)
.frame(width: geometry.size.width)
} 计算屏幕大小的容器

其他

属性包装器

未绑定属性就是公用状态
带上private表示只能在本结构体中使用,防止重名导致的崩溃
@State 值改变时,body内的内容重新刷新(双向绑定)
@Binding 将一个视图的属性链接到一些基础的模型数据
@ObservedObject 提取ObservableObject中储存的数据,所有页面共享数据
@Published 每当修改值时都会报告,willset{}可查看报告
@Environment(.Value) var Value 回到主页面
@EnvironmentObject 通过应用程序本身提供给视图,每个视图都可以读取的共享数据
.default 只实例化一次

协议

Identifiable 可以自动生成一个唯一标识符var id = UUID()

有用的View

地图View

import SwiftUI
import MapKit

struct MapView: UIViewRepresentable {

    func makeUIView(context: Context) -> MKMapView{
        MKMapView()
    }

    func updateUIView(_ uiView: MKMapView,context: Context)   {
        uiView.setRegion(MKCoordinateRegion(
            center: CLLocationCoordinate2D( //经度纬度
                latitude: 39.9087243,
                longitude: 116.3952859
                ),
            span: MKCoordinateSpan(
                latitudeDelta: 0.02,
                longitudeDelta: 0.02)),//地图区域大小(比例尺大小)
        animated: true)
    }
}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}

使用第三方库

下载并安装Cocoapods的教程

在APP中打开Podfile文件

在end上一行,写pod ‘第三方库的名字’
点install
库安装慢的教程

可以在Xcode中直接使用了

报错

[!] CocoaPods could not find compatible versions for pod “URLImage”:

解决方法:把.xcworkspace和Podfile.lock文件删除,重新pod install一下

装库的速度慢

给终端挂上梯子,在ssr里找到HTTP代理设置
在终端任意文件夹中输入HTTP的监听地址和监听端口

export https_proxy=http://127.0.0.1:1087
export http_proxy=http://127.0.0.1:1087