Swift Picker 绑定不会写入模型

问题描述 投票:0回答:1

在我的第一个 swift 应用程序中,

Picker
的数据绑定在模型的方向视图中不起作用。

class AppConfig: ObservableObject
{
    var _bpm: UInt = 115
    
    var bpm: String {
        get { return String(_bpm) }
        set { _bpm = UInt(newValue) ?? 0 }
    }
}

struct ContentView: View {
    @StateObject var midiCtrl = MidiControl()
    @StateObject var appConfig = AppConfig()
    
    var body: some View {
        VStack(alignment: .center) {
            Grid(alignment: .leadingLastTextBaseline) {
                GridRow {
                    Label("BPM", systemImage: "")
                        .gridColumnAlignment(.trailing)
                    Picker("Picker", selection: $appConfig.bpm) {
                        ForEach((80...120).reversed(), id: \.self) { idx in
                            Text(String(idx)).tag(String(idx))
                        }
                    }
                }
                Divider()
            }.padding()
        }
        .padding()
        .onAppear() {
            midiCtrl.openMidi()
        }
        .onDisappear() {
            midiCtrl.closeMidi()
        }
        .environmentObject(midiCtrl)
    }
}

最初,选择器预先选择了正确的值 (115)。

但是,当我尝试使用选择器更改值时,没有任何反应。

我认为 Swift UI 中使用

selection: $variable
语法的绑定是一种双向绑定。我错了吗?您是否需要手动添加类似
selectionChanged
之类的事件处理程序?

我也尝试了

@Published
@ObservedObject
,但我遇到了奇怪的编译器错误。

swift swiftui binding
1个回答
0
投票

当您有一个属性应该在符合

@Published
 的类中触发视图更新时,您应该使用 
ObservableObject

这里我简化了,直接用

UInt

class AppConfig: ObservableObject {
    @Published var bpm: UInt = 115
}

然后调整视图(再次简化)

struct ContentView: View {
    @StateObject var appConfig = AppConfig()

    var body: some View {
        Picker("Picker", selection: $appConfig.bpm) {
            ForEach((UInt(80)...UInt(120)).reversed(), id: \.self) { idx in
                Text(idx.formatted()).tag(idx)
            }
        }
        .padding()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.