I have a couple of nested views with nested viewModels that I need to ensure validation on.
Essentially ViewA has a form a Submit button and a Subview (ViewB) - the ViewModel for ViewB is contained within ViewB This architecture cannot change due to boring business reasons ViewB has some form fields. I need to ensure all the fields are valid in ViewA and ViewB before the Submit button is enabled.
I can't seem to figure out how to do this as any of the changes in ViewB are not triggering a refresh of ViewA
Here's some simplified code as a rough example
class ViewModelB: ObservableObject {
@Published var text = ""
@Published var textTwo = ""
func isValid() -> Bool {
!text.isEmpty && !textTwo.isEmpty
}
}
class ViewModelA: ObservableObject {
@Published var text = ""
@ObservedObject var addressViewModel: ViewModelB = ViewModelB()
func isValid() -> Bool {
print("is Valid called")
return !text.isEmpty && addressViewModel.isValid()
}
}
struct AddressView: View {
@ObservedObject var viewModel: ViewModelB
init(addressModel:ViewModelB) {
self.viewModel = addressModel
}
var body: some View {
TextField("View B Text", text: $viewModel.text)
TextField("View B TextTwo", text: $viewModel.textTwo)
}
}
struct ContentView: View {
@StateObject var viewModel: ViewModelA = ViewModelA()
var body: some View {
VStack {
TextField("View A Text", text: $viewModel.text)
AddressView(addressModel: viewModel.addressViewModel)
Button("Apply Button") {
print("Button tapped!")
}.disabled(!viewModel.isValid() || !viewModel.addressViewModel.isValid())
}
}
}