如何在 Swift 中的同一视图内的范围之间传递值?

How do I pass values between scopes inside the same View in Swift?

我想根据用户 select 做出决定,但我了解到我不能将与逻辑相关的代码放入视图中。现在,如何在另一个作用域中使用一个作用域的变量?

在给定的代码中,用户获得 select 他想提供给服务器的小费金额。我想根据服务员收到的小费显示一条消息。如何在代码的第 2 节中使用第 1 节中的变量 self.tipPercentages[0]

谢谢


struct ContentView: View {
    
    @State private var tipPercentage = 2
    
    @State var tipPercentages = [10, 15, 20, 25]
    @State var tipSelected = 0

    @State var if_10 = "okay, thanks"]
    @State var if_20 = "Wow, thank you!"


    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("How much tip do you want to leave?")) {      #<------ section1
                    Picker("Tip Percentage", selection: $tipPercentage) {
                        ForEach(0 ..< tipPercentages.count) {
                            Text("\(self.tipPercentages[[=11=]])%")
                            tip_selected = self.tipPercentages[0]  #<--- A varibale I want to use later
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }
                
                Section(header: Text("You decide to reward your server with [tip_selected %] tip")) {   #<------ section2
                    Text("[Thank you message]")
                }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        
    }
}

Pickerselection 参数将为您完成存储小费金额的工作——不需要 tipSelected = 行命令式代码。

然后,除非您打算在某个地方改变它们,否则 if_10if_20 并不需要成为 @State 变量。

这是一种可能的解决方案:

struct ContentView: View {
    @State var tipPercentages = [10, 15, 20, 25]
    @State var tipSelected = 0

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("How much tip do you want to leave?")) {
                    Picker("Tip Percentage", selection: $tipSelected) {
                        ForEach(tipPercentages, id: \.self) { tip in
                            Text("\(tip)%")
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }
                
                if tipSelected > 0 {
                    Section(header: Text("You decide to reward your server with \(tipSelected) tip")) {
                        Text(tipSelected < 20 ? "okay, thanks" : "Wow, thank you!")
                    }
                }
            }
        }
    }
}

如果您想从 20% 提示开始,您可以将 20 分配给 tipSelected 作为其初始值,而不是 0