Binding ViewModel and TextFields with SwiftUI
Here is possible approach (of course I don't have your custom views, so just replaced with standard, but the idea is the same). Tested with Xcode 11.2/iOS 13.2
class SignInViewModel: ObservableObject{
@Published var username:String? = nil
@Published var password:String? = nil
}
struct SigninView: View {
@ObservedObject var viewModel = SignInViewModel()
var body: some View {
VStack(alignment: .leading, spacing: 15.0){
TextField("username", text: Binding<String>(
get: {self.viewModel.username ?? ""},
set: {self.viewModel.username = $0}))
TextField("password", text: Binding<String>(
get: {self.viewModel.password ?? ""},
set: {self.viewModel.password = $0}))
Spacer()
Button("Sign In"){
print("User: \(self.viewModel.username)")
print("Pass: \(self.viewModel.password)")
}
}.padding()
}
}
I think we can simplify it with below code.
class SignInViewModel: ObservableObject{
@Published var username = ""
@Published var password = ""
}
struct SigninView: View {
@ObservedObject var viewModel = SignInViewModel()
var body: some View {
VStack(alignment: .leading, spacing: 15.0){
TextField("username", text: $viewModel.username)
TextField("password", text: $viewModel.password)
Spacer()
Button("Sign In"){
print("User: \(self.viewModel.username)")
print("Pass: \(self.viewModel.password)")
}
}.padding()
}
}