【发布时间】: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