使用Xcode 12访问SwiftUI中的ViewModel字段:“在视图上安装状态之外访问状态值”

deyfvvtc  于 2023-04-28  发布在  Swift
关注(0)|答案(2)|浏览(88)

我认为这个错误消息对于Xcode 12中的SwiftUI来说是新的,因为它在Google中给出了0次点击,而消息本身是相当通用的:
访问安装在视图之外的State值。这将导致初始值的固定Binding并且不会更新。
我有以下代码(删除了一些绒毛):

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
}

我曾经有field的权利在ContentView和工作正常。现在UI不再更新了,我得到了运行时警告。

1l5u6lss

1l5u6lss1#

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

vcudknz3

vcudknz32#

与另一个答案类似,AppView不同。您将得到相同的错误消息,但原因没有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."
        }
    }
}

对我来说,这个错误消息中的单词installed令人困惑。我希望他们能像这样,“访问一个没有在视图上定义的场景存储/状态值”。

相关问题