【问题标题】:Accessing ViewModel field in SwiftUI using Xcode 12: "Accessing State's value outside of being installed on a View"使用 Xcode 12 访问 SwiftUI 中的 ViewModel 字段:“访问安装在视图之外的状态值”
【发布时间】:2020-10-19 08:33:41
【问题描述】:

我认为这个错误消息对于 Xcode 12 中的 SwiftUI 来说是新的,因为它在 Google 中的点击率为 0,而消息本身相当通用:

在安装在 View 之外访问 State 的值。这将导致初始值的恒定绑定,并且不会更新。

我有以下代码(删除了一些绒毛):

public struct ContentView: View {
    @ObservedObject var model: RootViewModel

    public var body: some View {
        VStack(alignment: .center, content: {
            Picker(selection: model.$amount, label: Text("Amount")) {
                Text("€1").tag(1)
                Text("€2").tag(2)
                Text("€5").tag(5)
                Text("€10").tag(10)
            }.pickerStyle(SegmentedPickerStyle())
            Text("Donating: €\(model.amount)").font(.largeTitle)
        }).padding(.all, 20.0)
    }
}

public class RootViewModel: ObservableObject {
    @State public var amount: Int = 1
}

我曾经在ContentView 中拥有field,并且效果很好。现在 UI 不再更新,而我收到了运行时警告。

【问题讨论】:

  • State只能用在符合View的struct上,这里需要使用@Published

标签: swift swiftui combine xcode12


【解决方案1】:

感谢@Andrew 的回答,我想出了如何让它再次工作。首先你把@State改成@Published

    @Published public var amount: Int = 1

接下来,您需要更改Picker 与数据的绑定方式:

            Picker(selection: $model.amount, label: Text("Amount")) {
                Text("€1").tag(1)
                Text("€2").tag(2)
                Text("€5").tag(5)
                Text("€10").tag(10)
            }.pickerStyle(SegmentedPickerStyle())

所以我们从model.$amount 转到$model.amount

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-24
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多