这是一个简单的基于 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))"
}
}
从视图模型内部更新模型时,视图不会更新。文本最终应该会产生一些介于 1 和 10 之间的随机数。请让我知道我哪里出错了。