@State and @Binding work so well in SwiftUI, as long as you put all the view's data inside itself, like this:
struct ColorView: View {
@Binding public var isBlue: Bool
var body: some View {
Rectangle()
.foregroundColor(isBlue ? .blue : .red)
.onTapGesture {
self.isBlue.toggle()
}
}
}
struct TestView: View {
@State var isBlue: Bool = false
var body: some View {
ColorView(isBlue: $isBlue)
}
}
It works without a problem and it's really simple. But MVVM says you should put all of the view's data inside a view model class, to separate UI from the model. But then you lose @State and @Binding completely. You lose this 2-way binding it seems. Sure, you can do it manually with Combine or something but that should not be the correct way, right?
Whenever I try anything, SwiftUI is really easy and convenient when you don't use view models. Once you put everything inside a view model class, though, everything breaks down and nothing works as convenient anymore. This can't be the case, they have to had thought of that. So I'm missing something here. I'd really appreciate any help. How would you code the above's example using view models (without "hacking" anything manually)? I tried but it doesn't even compile:
struct ColorView: View {
@ObservedObject var viewModel: ViewModel
class ViewModel: ObservableObject {
// Binding or Published? Both doesn't seem to work
@Binding var isBlue: Bool
init(isBlue: Binding<Bool>) { // Or type Bool? But then we lose the binding
self.$isBlue = isBlue
}
}
var body: some View {
Rectangle()
.foregroundColor(viewModel.isBlue ? .blue : .red)
.onTapGesture {
self.viewModel.isBlue.toggle()
}
}
}
struct TestView: View {
@ObservedObject var viewModel: ViewModel
class ViewModel: ObservableObject {
@Published var isBlue: Bool = false // We would need a @State here, but then we lose @Published
}
var body: some View {
ColorView(viewModel: .init(isBlue: /* ??? */)) // How to pass a binding here`
}
}
Do I think of this the wrong way?
Thanks!