我正在使用SwiftUI和Combine创建一个新的watchOS应用程序,尝试使用MVVM架构,但是当我的viewModel更改时,我似乎无法使视图中的Text视图更新。我在使用watchOS 6、SwiftUI和Combine。我已经在我认为应该使用@ObservedObject和@Published的地方使用了它们,但是变化并没有像我预期的那样反映出来。
// Simple ContentView that will push the next view on the navigation stack
struct ContentView: View {
var body: some View {
NavigationLink(destination: NewView()) {
Text("Click Here")
}
}
}
struct NewView: View {
@ObservedObject var viewModel: ViewModel
init() {
viewModel = ViewModel()
}
var body: some View {
// This value never updates
Text(viewModel.str)
}
}
class ViewModel: NSObject, ObservableObject {
@Published var str = ""
var count = 0
override init() {
super.init()
// Just something that will cause a property to update in the viewModel
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
self?.count += 1
self?.str = "\(String(describing: self?.count))"
print("Updated count: \(String(describing: self?.count))")
}
}
}
Text(viewModel.str)
从未更新,即使viewModel每1.0秒递增一个新值。我已经尝试在属性更新时使用objectWillChange.send()
,但什么都没有发生。
我做错了什么吗?
Timer
过早地被释放。保持对计时器对象的强引用,那就可以解决问题了。请参阅此处。 - nayem