我正在尝试实现一个自定义选取器,使自定义值可供父级使用(而不是仅选择索引)。在下面的示例中,我有一个绑定(bind)到选择器上的 selection
的 @State
变量以及一个可以正确更新的计算变量 selectedOption
。
import SwiftUI
struct CustomPicker: View {
var options = ["option1", "option2", "option3"]
@State var selectedIndex = 0
var selectedOption {
options[selectedIndex]
}
var body: some View {
Picker(selection: $selectedIndex, label: Text("")) {
ForEach(0..<self.options.count) { index in
Text("\(self.options[index])").tag(index)
}
}.pickerStyle(SegmentedPickerStyle())
}
}
但是,我希望能够在另一个 View 中与 CustomerPicker
交互,如下所示:
@State var selectedOption: string;
...
CustomPicker(selectedOption: $selectedOption)
因此父 View 直接处理选项,而不是索引。有谁对我如何使用 SwiftUI 解决这个问题有任何建议吗?
最佳答案
您的自定义选择器需要 @Binding
到所选索引。我认为为选择器本身提供“无选择”选项也是一个好主意:
struct CustomPicker: View {
var options = ["option1", "option2", "option3"]
@Binding var selectedIndex: Int?
var body: some View {
Picker(selection: $selectedIndex,
label: Text("")) {
Text("no selection")
.tag(Optional<Int>.none)
ForEach(0..<self.options.count) { index in
Text("\(self.options[index])")
.tag(index)
}
} .pickerStyle(SegmentedPickerStyle())
}
}
关于ios - 自定义选择器可以访问选项值,而不仅仅是选定的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59124712/