当前位置: 首页>编程语言>正文

100 Days of SwiftUI - Day 17 项目1-2

效果图


100 Days of SwiftUI - Day 17 项目1-2,第1张
截屏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("\() people")
                        }
                    }
                }
                
                Section(header: Text("How much tip do you want to leave?")) {
                    Picker("Tip percentage", selection: $tipPercentage) {
                        ForEach(0 ..< tipPercentages.count) {
                            Text("\(self.tipPercentages[])%")
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }
                
                Section {
                    // 3.使用字符串插值的方式,限定字符串的格式
                    Text("$\(totalPerPerson, specifier: "%.2f")")
                }
            }
            .navigationTitle("WeSplit")
        }
    }
}

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


https://www.xamrdz.com/lan/5uv1997550.html

相关文章: