100 Days of SwiftUI

100 Days of SwiftUI - Day 17 项目1

2020-10-16  本文已影响0人  星星星宇

效果图


截屏2020-10-16 上午10.33.43.png

代码如下

struct ContentView: View {

    @State private var checkAmount = ""
    @State private var numberOfPeople = 2
    @State private var tipPercentage = 2
    
    let tipPercentages = [10, 15, 20, 25, 0]
    
    // 1. 变化的三个属性都标有@State,所以在发生变化时,totalPerPerson属性会立即计算
    var totalPerPerson: Double {
        let peopleCount = Double(numberOfPeople + 2)
        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0
        let tipValue = orderAmount / 100 * tipSelection
        let grandTotal = orderAmount + tipValue
        let amountPerson = grandTotal / peopleCount
        return amountPerson
    }
    
    var body: some View {
        
        NavigationView {
            Form {
                Section {
                    TextField("Amount", text: $checkAmount)
                        .keyboardType(.decimalPad)
                    
                    // 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 {
                    // 3.使用字符串插值的方式,限定字符串的格式
                    Text("$\(totalPerPerson, specifier: "%.2f")")
                }
            }
            .navigationTitle("WeSplit")
        }
    }
}

代码有三处需要注意的地方
1.@State声明的属性变化时,会使计算属性重新计算。
2.Form内的Picker,需要NavigationView跳转下个页面。
3.字符串插值的方式限定数字格式。

上一篇 下一篇

猜你喜欢

热点阅读