SwiftUI根据选择器的String结果设置Binding

时间:2019-08-28 15:48:51

标签: ios swiftui picker

我正在拔头发,试图弄清楚如何在SwiftUI视图中绑定选择的值:

选择器需要绑定到从标签返回的Int上。我需要将此Int转换为String并设置Binding。怎么样?

struct ContentView: View {

   @Binding var operatorValueString:String

    var body: some View {

         Picker(selection: queryType, label: Text("Query Type")) {
             ForEach(0..<DM.si.operators.count) { index in
                 Text(DM.si.operators[index]).tag(index)
             }
         }.pickerStyle(SegmentedPickerStyle())
    }
}

如何以及在何处设置我的operatorValueString?

  

operatorValueString = DM.si.operators [queryType] //不会编译。

1 个答案:

答案 0 :(得分:4)

只要选择器的选择发生更改,就可以使用您自己的自定义绑定来设置字符串,从而获得结果。

struct ContentView: View {
    @State private var operatorString = ""

    var body: some View {
        VStack {
            Subview(operatorValueString: $operatorString)
            Text("Selected: \(operatorString)")
        }
    }
}

struct Subview: View {
    @Binding var operatorValueString: String
    @State private var queryType: Int = 0

    let operators = ["OR", "AND", "NOT"]

    var body: some View {

        let binding = Binding<Int>(
            get: { self.queryType },
            set: {
                self.queryType = $0
                self.operatorValueString = self.operators[self.queryType]
            })

        return Picker(selection: binding, label: Text("Query Type")) {
            ForEach(operators.indices) { index in
                Text(self.operators[index]).tag(index)
            }
        }.pickerStyle(SegmentedPickerStyle())
    }
}