I am facing a problem with property changes are not being watched in my view. The problem appears when I use class. However, when I use Struct instead of class the problem is solved.
Code which is working:
struct DetailsModel {
var dayState : Bool
init() {
dayState = true
}
}
class ViewModel : ObservableObject{
@Published var charge = DetailsModel()
}
struct ContentView: View {
//@StateObject var viewModel = ViewModel()
@StateObject var viewModel = ViewModel()
var body: some View {
VStack{
HStack{
Text(viewModel.charge.dayState == true ? "Day" : "Night")
.padding()
Button.init {
viewModel.charge.dayState.toggle()
} label: {
Text("Toggle")
}
}
}
}
}
When I tap the Toggle Button, the text views are changing Day/Night.
Code which is not working:
I replace the struct with class and it's not updating the view.
class DetailsModel: ObservableObject {
@Published var dayState : Bool
init() {
dayState = true
}
}
My question is As I already using ObserableObject and as well as Published properties in Details class, it should be watch the object , why its not observing anything from the View?