使用Xcode 12访问SwiftUI中的ViewModel字段: [英] Accessing ViewModel field in SwiftUI using Xcode 12: "Accessing State's value outside of being installed on a View"
问题描述
我认为此错误消息是Xcode 12中SwiftUI的新增功能,因为它在Google中获得了0次匹配,而消息本身却是相当通用的:
I think this error message is new to SwiftUI in Xcode 12 since it gave 0 hits in Google while the message itself is fairly generic:
在安装到View之外访问State的值.这将导致初始值的恒定绑定,并且不会更新.
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.
我有以下代码(删除了一些绒毛):
I have the following code (removed some fluff):
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
的权限,并且一切正常.现在用户界面不再更新,而是收到了运行时警告.
I used to have the field
right in the ContentView
and that worked alright. Now the UI does not update anymore and I got that run-time warning instead.
推荐答案
由于@Andrew的回答,我弄清楚了如何使其再次工作.首先,将 @State
更改为 @Published
:
Thanks to @Andrew's answer I figured out how to make it work again. First you change the @State
to @Published
:
@Published public var amount: Int = 1
接下来,您需要更改将 Picker
绑定到数据的方式:
Next, you need to change how you Picker
is bound to the data:
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
.
这篇关于使用Xcode 12访问SwiftUI中的ViewModel字段:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!