筆記
本篇文章記錄一下100 Days of SwiftUI第17-18天的筆記內(nèi)容
使用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獲取當前用戶的區(qū)域設置
// 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也會顯示小數(shù)
}
}
}
在表單中創(chuàng)建選擇器
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 人”,但我們?yōu)閚umberOfPeople屬性指定了默認值 2
// 問題一需要添加NavigationView才能跳轉(zhuǎn)到新視圖
// 問題二是因為使用了ForEach(2 ..< 100),從2開始創(chuàng)建,所以認為第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 與常規(guī)屬性完全相同@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() // 靈活的空間,自動將其他視圖推到一側(cè)
amountIsFocused = false
}
}
}
總結(jié)
在此項目中,學習到了SwiftUI應用程序的基本結(jié)構、如何構建表單、創(chuàng)建導航視圖和導航欄標題、如何使用屬性包裝器存儲程序狀態(tài)、如何創(chuàng)建用戶界面控件(例如@State和@FocusState)TextField以及Picker,如何使用ForEach循環(huán)創(chuàng)建視圖。