笔记
本篇文章记录一下100 Days of SwiftUI
第17-18天的笔记内容
使用TextField读取用户的文本
@State private var checkAmount = 0.0
@State private var numberOfPeople = 2
@State private var tipPercentage = 20
var body: some View {
Form {
Section {
// TextField除了可以用Text还可以用Value传递Double型
// .currency可以将输入视为货币
TextField("Amount", value: $checkAmount, format: .currency(code: "USD"))
// 可以通过Locale获取当前用户的区域设置
// TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD")))
}
}
}
var body: some View {
Form {
Section {
TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
}
Section {
TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
.keyboardType(.decimalPad) //.decimalPad也会显示小数
}
}
}
在表单中创建选择器
var body: some View {
Form {
Section {
TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
.keyboardType(.decimalPad)
Picker("Number of people", selection: $numberOfPeople) {
ForEach(2 ..< 100) {
Text("\($0) people")
}
}
}
}
}
// 存在两个问题
// 1.点击该行不会显示另一个屏幕
// 2.该行显示“4 人”,但我们为numberOfPeople属性指定了默认值 2
// 问题一需要添加NavigationView才能跳转到新视图
// 问题二是因为使用了ForEach(2 ..< 100),从2开始创建,所以认为第1行是“4 人”,选中的第3行就是“4 人”
添加小费百分比的分段控件
// .pickerStyle(.segmented) 分段控件
Section {
Picker("Tip percentage", selection: $tipPercentage) {
ForEach(tipPercentages, id: \.self) {
Text($0, format: .percent)
}
}
.pickerStyle(.segmented)
}
计算每人总计
var totalPerPerson: Double {
let peopleCount = Double(numberOfPeople + 2)
let tipSelection = Double(tipPercentage)
let tipValue = checkAmount / 100 * tipSelection
let grandTotal = checkAmount + tipValue
let amountPerPerson = grandTotal / peopleCount
return amountPerPerson
}
Section {
Text(totalPerPerson, format: .currency(code: Locale.current.currencyCode ?? "USD"))
}
// 由于构成总计的所有值都标有@State,因此更改其中任何一个值都会导致自动重新计算总计
隐藏键盘
// 文本框是否有焦点
// @FocusState 与常规属性完全相同@State,只不过它是专门为处理UI中的输入焦点而设计的
@FocusState private var amountIsFocused: Bool
TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
.keyboardType(.decimalPad)
.focused($amountIsFocused)
// 键盘上添加按钮移除文本框焦点,隐藏键盘
.toolbar { // 可以指定视图的工具栏项
ToolbarItemGroup(placement: .keyboard) { // 指定要一个键盘工具栏
Button("Done") {
Spacer() // 灵活的空间,自动将其他视图推到一侧
amountIsFocused = false
}
}
}
总结
在此项目中,学习到了SwiftUI应用程序的基本结构、如何构建表单、创建导航视图和导航栏标题、如何使用属性包装器存储程序状态、如何创建用户界面控件(例如@State和@FocusState)TextField以及Picker,如何使用ForEach循环创建视图。