我认为这个错误消息对于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不再更新了,我得到了运行时警告。
2条答案
按热度按时间1l5u6lss1#
感谢@Andrew的回答,我想出了如何让它再次工作。首先,将
@State
更改为@Published
:接下来,您需要更改
Picker
绑定到数据的方式:所以我们从
model.$amount
到$model.amount
。vcudknz32#
与另一个答案类似,
App
与View
不同。您将得到相同的错误消息,但原因没有OP示例中那么明显。对我来说,这个错误消息中的单词installed令人困惑。我希望他们能像这样,“访问一个没有在视图上定义的场景存储/状态值”。