在項(xiàng)目1的基礎(chǔ)上修改以下內(nèi)容
1.在第三個(gè)section添加標(biāo)題,即“Amount total”
2.添加另一section以顯示支票的總金額,即原始金額加上小費(fèi)值,而不用人數(shù)來(lái)劃分。
3.將“人數(shù)”選擇器更改為文本字段,并確保使用正確的鍵盤(pán)類型。
代碼如下
struct ContentView: View {
@State private var checkAmount = ""
@State private var numberOfPeople = 2
@State private var countOfPeople = "2"
@State private var tipPercentage = 2
let tipPercentages = [10, 15, 20, 25, 0]
// 1. 變化的三個(gè)屬性都標(biāo)有@State,所以在發(fā)生變化時(shí),totalPerPerson屬性會(huì)立即計(jì)算
var totalPerPerson: Double {
let peopleCount = Double(countOfPeople) ?? 1
let amountPerson = totalAmount / peopleCount
return amountPerson
}
var totalAmount: Double {
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
let tipValue = orderAmount / 100 * tipSelection
let grandTotal = orderAmount + tipValue
return grandTotal
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Amount", text: $checkAmount)
.keyboardType(.decimalPad)
TextField("Number of people", text: $countOfPeople)
.keyboardType(.numberPad)
// 2. 位于表單內(nèi)部的Picker會(huì)自動(dòng)選擇,列表選擇方式,所以需要一個(gè)NavigationView
// Picker("Number of people", selection: $numberOfPeople) {
// ForEach(2 ..< 100) {
// Text("\($0) people")
// }
// }
}
Section(header: Text("How much tip do you want to leave?")) {
Picker("Tip percentage", selection: $tipPercentage) {
ForEach(0 ..< tipPercentages.count) {
Text("\(self.tipPercentages[$0])%")
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Amount total")) {
// 3.使用字符串插值的方式,限定字符串的格式
Text("$\(totalAmount, specifier: "%.2f")")
}
Section(header: Text("Amount per person")) {
// 3.使用字符串插值的方式,限定字符串的格式
Text("$\(totalPerPerson, specifier: "%.2f")")
}
}
.navigationTitle("WeSplit")
}
}
}