简体   繁体   中英

SwiftUI view not getting updated on changing @ObservedObject

Here is a simple MVVM based 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))"
    }
}

The view does not get updated when the model is updated from inside the view model. The text should finally produce some random number between 1 and 10. Please let me know where I am going wrong.

It is because your Test view observes viewModel but not viewModel.model which is not changed in your scenario because it is a reference-type

The following is a solution

func change() {
    model.condition.toggle()
    model.stri = "\(Int.random(in: 1...10))"

    self.objectWillChange.send()    // << this one !!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM