吐槽
Day13-15是复习,看了下,有些小技巧,原文链接在这里
这个project是做一个AA付款的程序,用来计算每个人要给多少钱。直接跳过一堆介绍,开始代码。
本文参考资料:
https://www.hackingwithswift.com/100/swiftui/16
时间:12 October, 2020
快捷键
运行快捷键:command+R
刷新:option+command+P
隐藏/显示preview:option+command+回车
将preview转为代码(恢复用上面的显示preview):control+option+command+回车
删除当前行:option+D
表格 - Form
SwiftUI有个限制:最多只能放十个children在parent里面,所以超过10个之后就不行了。比如,下方的Form不能直接放十个以上,会报错,此时需要分成group或者section。
var body: some View {
Form {
Text("Hello World")
}
}
- Group
Form {
Group {
Text("Hello World")
Text("Hello World")
Text("Hello World")
Text("Hello World")
Text("Hello World")
Text("Hello World")
}
Group {
Text("Hello World")
Text("Hello World")
Text("Hello World")
Text("Hello World")
Text("Hello World")
}
}
- Section
Form {
Section {
Text("Hello World")
}
Section {
Text("Hello World")
Text("Hello World")
}
}
导航栏 - navigation bar
更新之后displayMode换成这样子了。
状态 - @State
记得加上private控制访问权限
struct SecondPage: View {
@State private var tapCount = 0
var body: some View {
NavigationView{
Button("Taped \(tapCount) Times"){
self.tapCount += 1
}
}
}
}
$捆绑 - Binding State
注意变量类型,以及使用时变量前面的$符号
struct SecondPage: View {
@State private var country = ""
var body: some View {
Form{
TextField("Enter your Country", text: $country)
Text("You are from \(country).")
}
}
}
循环创建控件
不知道为什么,Picker第一个参数用不了,只能在前面加一个Text了。
struct SecondPage: View {
var Countries = ["China", "England", "America", "Japan", "Australia"]
@State private var selectedCountry = 2
var body: some View{
VStack{
Text("Select a country")
Picker("", selection: $selectedCountry){
ForEach(0 ..< Countries.count){ index in
Text(Countries[index])
}
}
Text("Your Choice is \(Countries[selectedCountry])")
}
}
}
效果