SwiftUI魔术的坏情况对我不起作用,我在这里失去了理智。为什么文本在这里不更新其值?为什么每次increment()
通话后都没有重新评估身体?
class ReadingStateVM: ObservableObject {
@Published var value = 0
func increment() {
value = value + 1
print("value \(value)")
}
}
struct ReadingStateView: View {
var viewModel = ReadingStateVM()
var body: some View {
Text("State \(viewModel.value)")
.onTapGesture {
self.viewModel.increment()
}
}
}
答案 0 :(得分:1)
您需要添加@ObservedObject
属性包装器,以便在视图模型发生更改时,视图也将更新。
@ObservedObject var viewModel = ReadingStateVM()