SwiftUI @State 奇怪的wrappedValue 行为

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

所以直接说重点,我有这段代码:

struct DataModel {
    var option: String

}

struct ViewModel {
    var selected: String? = "1"
    var options = [DataModel(option: "1"), DataModel(option: "2"), DataModel(option: "3")]
}

struct ContentView: View {
    
    @State var viewModel: ViewModel
    
    var body: some View {
        VStack {
            Picker("test", selection: aBinder()) {
                ForEach(viewModel.options, id: \.option) { option in
                    Text(option.option)
                }
            }
            .background(Color.red)
        }
    }
    
    func aBinder() -> Binding<String?> {
        Binding<String?> {
            viewModel.selected
        } set: { value in
            $viewModel.selected.wrappedValue = value
            print($viewModel.selected.wrappedValue)
        }
    }
}

viewModel 中“selected”的值不会改变。

这有效:

struct DataModel {
    var option: String
}

struct ViewModel {
    var selected: String = "1"
    var options = [DataModel(option: "1"), DataModel(option: "2"), DataModel(option: "3")]
}

struct ContentView: View {
    
    @State var viewModel: ViewModel
    
    var body: some View {
        VStack {
            Picker("test", selection: $viewModel.selected) {
                ForEach(viewModel.options, id: \.option) { option in
                    Text(option.option)
                }
            }
            
            Button("press me", action: { print(viewModel.selected) })
        }
    }
}

但这没有任何意义。在这两种情况下,我都使用绑定来存储当前值。到底是怎么回事?我对 swiftUI 还很陌生,所以我可能错过了一些东西是如何工作的。

提前致谢

swiftui binding picker
1个回答
1
投票

类型不匹配

selected
String
,而
options
DataModel
。类型必须完全匹配。

© www.soinside.com 2019 - 2024. All rights reserved.