ios – Adding view model causes view updates to fail


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:

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

        objectWillChange.send()

    }
}

struct ContentView: View {
    @ObservedObject var viewModel: ViewModel
    
    var body: some View {
        VStack {
            Text("Your score is \(viewModel.score)")
            Button("Increase Score") {
                viewModel.incScore()
            }
        }
    }
}

Or you can consider using @Published in the following way:

 class ViewModel: ObservableObject {
    private var model: Model
    @Published var score: Int

    init() {
        model = Model()
        score = model.score
    }

    func incScore() {
        model.score += 1
        score = model.score
        
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img