【问题标题】:SwiftUI @State wierd wrappedValue behaviourSwiftUI @State 奇怪的 WrappedValue 行为
【发布时间】:2022-01-07 06:48:45
【问题描述】:

直截了当,我有这个代码:

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 很陌生,所以我可能错过了一些工作原理。

提前致谢

【问题讨论】:

  • 我认为你可以只做“viewModel.selected.wrappedValue = value”。 $ 是当你想将 @State 的引用传递给另一个视图时。
  • 感谢您的建议@Aheze 但是 WrappedValue 仅在绑定和状态上。这意味着我不得不说 viewModel.selected = value。但它是一个结构,它是不可变的:/
  • 选择不匹配的类型是字符串,选项是数据模型。类型必须完全匹配。在this
  • @Vollan,对不起,我的意思是“viewModel.selected = value”。 IIRC 即使它是一个结构也应该可以工作,因为“viewModel”是一个状态并且它们是特殊的
  • 阿赫兹,是的。状态是不同的,但是由于状态本身是具有子值的结构,因此它不起作用:/。 @loremipsum 谢谢。它在我的测试代码中工作。我将在明天现场试用并提供反馈。如果您想要一些分数,请写下答案;)

标签: swiftui binding picker


【解决方案1】:

类型不匹配 selectedStringoptionsDataModel。类型必须完全匹配。

【讨论】:

    猜你喜欢
    • 2022-12-15
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多