Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

ios - 可以访问选项值而不是仅选择索引的自定义选择器(Custom picker with access to option value instead of just selected index)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your custom picker needs @Binding to the selected index.

(您的自定义选择器需要@Binding到所选索引。)

I think it would also be a good idea to offer a "no selection" option to the picker itself:

(我认为为选择器本身提供“不选择”选项也是一个好主意:)

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())
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...