I'm trying to implement a custom Picker that makes a custom value available to the parent (as opposed to just the selected index).
(我正在尝试实现一个自定义选择器,该自定义选择器使自定义值可用于父级(而不只是选定的索引)。)
In the example below, I've got a @State
variable bound to selection
on the picker as well as a computed variable selectedOption
which updates correctly. (在下面的示例中,我在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())
}
}
However, I want to be able to interact with the CustomerPicker
in another view like this:
(但是,我希望能够在另一个视图中与CustomerPicker
进行交互,如下所示:)
@State var selectedOption: string;
...
CustomPicker(selectedOption: $selectedOption)
So that the parent view is dealing with the option directly, as opposed to the index.
(因此父视图直接处理选项,而不是索引。)
Does anyone have any tips as to how I would go about this using SwiftUI? (有谁对我如何使用SwiftUI进行操作有任何提示?)
ask by Sam Turner translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…