I’m attempting to separate my model and view by adding a view model as a bridge. When I do this in the following code, clicking on the ‘Increase Score’ button no longer triggers a view update. It works if I connect the view directly to the model. Any suggestions on how to get this to work?
import SwiftUI
@main
struct MVVM_Test_Watch_AppApp: App {
@StateObject var viewModel = ViewModel()
var body: some Scene {
WindowGroup {
ContentView(viewModel: viewModel)
}
}
}
class Model {
var score = 0
}
class ViewModel: ObservableObject {
@Published private var model: Model
init() {
model = Model()
}
var score: Int {
model.score
}
func incScore() {
model.score += 1
}
}
struct ContentView: View {
@ObservedObject var viewModel: ViewModel
var body: some View {
VStack {
Text("Your score is (viewModel.score)")
Button("Increase Score") {
viewModel.incScore()
}
}
}
}
2
Answers
According to this migration page, there's a new way to handle observation. I updated and tested my code.
Typically, in models within SwiftUI,
struct
is used, and while this might not be the exact cause of the issue you’re encountering.In your code, a minimal change to detect updates and refresh the view would be to add
objectWillChange.send()
to the function. Here’s a sample code for reference:Or you can consider using
@Published
in the following way: