I'm looking for the best way to create a bind between textfields
and ViewModel
.
At the moment I'm creating a @State
for each textfield and I'm manually sending the value from textfield to the viewModel properties when needed. I'm pretty sure this is not the best way to go... Is there a way to bind the TextField
with the ViewModel
property?
This is my current code:
struct SigninView: View {
@State var username:String = ""
@State var password:String = ""
var viewModel:SignInViewModel
var body: some View {
VStack(alignment: .leading, spacing: 15.0){
DefaultTextField(placeholder: "username", value: $username)
DefaultTextField(placeholder: "password", value: $password)
Spacer()
FillButton(title:"Sign In"){
///// IS THIS CORRECT?
self.viewModel.email = self.username
self.viewModel.password = self.password
//------------------
self.viewModel.signin()
}
}.padding()
}
}
The view model is something like:
class SignInViewModel:ObservableObject{
var username:String? = nil
var password:String? = nil