我正在撕扯头发,试图弄清楚如何在我的 SwiftUI View 中绑定(bind)选择的值:
选择器需要绑定(bind)到标签返回的 Int。我需要将此 Int 转换为字符串并设置绑定(bind)。如何?
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] //won't compile.
最佳答案
You can achieve the result, using your own custom binding that sets the string, whenever the picker's selection changes:
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())
}
}
关于ios - SwiftUI 从选择器的字符串结果中设置绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57696082/