首页 > 解决方案 > SwiftUI PickerView 与工作回调如何?

问题描述

好的 -

我想要一个选择器视图来选择一个运算符:“=”,“<”,“>”这个运算符将作为绑定发送:

@Binding var op:String

我的选择器:

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

现在我与回调的绑定:

let binding = Binding<Int>(
    get: {
        return self.pickerSelection
    },
    set: {
        //pickerSelection = $0
        print("SETTTING: \($0)")
        self.op = self.operators[self.pickerSelection]
        self.queryCallback()

    })

所以,我可以完美地设置选择器。但是,当我回去编辑我的数据时,选择器永远不能选择现有的绑定运算符,比如“<”

我在初始化中放入:
pickerSelection = operator.firstIndex(opValue)

然而,这只会启动一个无限循环,因为 pickerSelection 是一个 @State 变量

有人有解决方案吗?

标签: swiftuipickerpickerview

解决方案


这是一种行之有效的方法。它使用 Combine 来制作一个可观察的,可以用来触发所需的事件。我还看到了 Combine 对 SwiftUI 有多么有用

https://stackoverflow.com/a/57519105/810300


推荐阅读