100 Days of SwiftUI - Day 18 項(xiàng)目1-3

在項(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")
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容