筆記
本篇文章記錄一下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獲取當(dāng)前用戶的區(qū)域設(shè)置
// 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也會(huì)顯示小數(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")
}
}
}
}
}
// 存在兩個(gè)問題
// 1.點(diǎn)擊該行不會(huì)顯示另一個(gè)屏幕
// 2.該行顯示“4 人”议谷,但我們?yōu)閚umberOfPeople屬性指定了默認(rèn)值 2
// 問題一需要添加NavigationView才能跳轉(zhuǎn)到新視圖
// 問題二是因?yàn)槭褂昧薋orEach(2 ..< 100)锐峭,從2開始創(chuàng)建,所以認(rèn)為第1行是“4 人”颜启,選中的第3行就是“4 人”
添加小費(fèi)百分比的分段控件
// .pickerStyle(.segmented) 分段控件
Section {
Picker("Tip percentage", selection: $tipPercentage) {
ForEach(tipPercentages, id: \.self) {
Text($0, format: .percent)
}
}
.pickerStyle(.segmented)
}
計(jì)算每人總計(jì)
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"))
}
// 由于構(gòu)成總計(jì)的所有值都標(biāo)有@State,因此更改其中任何一個(gè)值都會(huì)導(dǎo)致自動(dòng)重新計(jì)算總計(jì)
隱藏鍵盤
// 文本框是否有焦點(diǎn)
// @FocusState 與常規(guī)屬性完全相同@State,只不過它是專門為處理UI中的輸入焦點(diǎn)而設(shè)計(jì)的
@FocusState private var amountIsFocused: Bool
TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
.keyboardType(.decimalPad)
.focused($amountIsFocused)
// 鍵盤上添加按鈕移除文本框焦點(diǎn),隱藏鍵盤
.toolbar { // 可以指定視圖的工具欄項(xiàng)
ToolbarItemGroup(placement: .keyboard) { // 指定要一個(gè)鍵盤工具欄
Button("Done") {
Spacer() // 靈活的空間璧尸,自動(dòng)將其他視圖推到一側(cè)
amountIsFocused = false
}
}
}
總結(jié)
在此項(xiàng)目中,學(xué)習(xí)到了SwiftUI應(yīng)用程序的基本結(jié)構(gòu)熬拒、如何構(gòu)建表單爷光、創(chuàng)建導(dǎo)航視圖和導(dǎo)航欄標(biāo)題、如何使用屬性包裝器存儲(chǔ)程序狀態(tài)澎粟、如何創(chuàng)建用戶界面控件(例如@State和@FocusState)TextField以及Picker蛀序,如何使用ForEach循環(huán)創(chuàng)建視圖。