使用 Xcode 12 在 SwiftUI 中访问 ViewModel 字段:"Accessing State's value outside of being installed on a View"

Accessing ViewModel field in SwiftUI using Xcode 12: "Accessing State's value outside of being installed on a View"

我认为此错误消息是 Xcode 12 中 SwiftUI 的新消息,因为它在 Google 中给出了 0 次命中,而消息本身相当通用:

Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update.

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

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 不再更新,我收到了 运行 时间警告。

感谢@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

与其他答案类似,App 不同于 View。您将收到相同的错误消息,但原因不如 OP 示例中的那么明显。

@main
struct MyCoolApp: App {
    @SceneStorage("testSceneStorage") private var persisted = ""

    var body: some Scene {
        WindowGroup {
            Text(persisted) // "Accessing a SceneStorage value outside of being installed on a View. This will always return the default value."
        }
    }
}

对我而言,此错误消息中的安装一词令人困惑。我希望他们能处理类似“访问未在视图上定义的 SceneStorage/State 值”之类的内容。