The code below does not update when I call viewModel.updateToBanana(). How can I update the view when I set model.title to Banana.
This is my code:
class MyModel: ObservableObject {
@Published var title: String = ""
init(title: String) {
self.title = title
}
}
class MyViewModel: ObservableObject {
@Published var model = MyModel(title: "Apple")
func updateToBanana() {
model.title = "Banana"
}
}
struct MyView: View {
@StateObject var viewModel = MyViewModel()
var body: some View {
VStack(spacing: 20) {
Text(viewModel.model.title)
Button {
viewModel.updateToBanana()
} label: {
Text("Banana")
}
}
}
}
I have tried to change @Published to @ObservedObject, but it did not work.
updateToBananain your example, suggest renaming the functionupdateor correcting the function call.Observationframework. Then you can nest the observed classes. See Managing model data. If you want to keep the older system, other ways to use nestedObservableObjectclasses, see stackoverflow.com/questions/58406287/…