这是一个简单的基于 MVVM 的 TestView:
import SwiftUI
public struct Test: View {
@ObservedObject public var viewModel = TestViewModel()
public init() {
}
public var body: some View {
VStack {
Text(viewModel.model.stri)
Button(action: {
self.viewModel.change()
}) {
Text("Change")
}
}.padding(50)
}
}
public class TestModel {
@Published public var condition: Bool = false
@Published var stri = "Random numbers"
}
public class TestViewModel: ObservableObject {
@Published var model = TestModel()
func change() {
model.condition.toggle()
model.stri = "\(Int.random(in: 1...10))"
}
}
从 View 模型内部更新模型时, View 不会更新。文本最终应该会产生一些介于 1 和 10 之间的随机数。请让我知道我哪里出错了。
最佳答案
这是因为您的Test
查看观察 viewModel
但不是 viewModel.model
在您的场景中不会更改,因为它是引用类型
以下是解决方案
func change() {
model.condition.toggle()
model.stri = "\(Int.random(in: 1...10))"
self.objectWillChange.send() // << this one !!
}
关于ios - SwiftUI View 在更改 @ObservedObject 时未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62682422/