在项目1的基础上修改以下内容
1.在第三个section添加标题,即“Amount total”
2.添加另一section以显示支票的总金额,即原始金额加上小费值,而不用人数来划分。
3.将“人数”选择器更改为文本字段,并确保使用正确的键盘类型。
代码如下
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. 变化的三个属性都标有@State,所以在发生变化时,totalPerPerson属性会立即计算
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. 位于表单内部的Picker会自动选择,列表选择方式,所以需要一个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")
}
}
}