Created
October 30, 2021 10:45
-
-
Save disc0infern0/1246af4f52c2dad1d68ad8fcfc744414 to your computer and use it in GitHub Desktop.
Login form demonstrating change of focus using a view model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LoginViewModel: ObservableObject { | |
@Published var username = "" | |
@Published var password = "" | |
@Published var focusedField: Field? | |
enum Field: Hashable { | |
case username | |
case password | |
} | |
func signInButtonTapped() { // async { | |
if username.isEmpty { | |
focusedField = .username | |
} else if password.isEmpty { | |
focusedField = .password | |
} else { | |
self.focusedField = nil | |
// handle login | |
} | |
} | |
} | |
struct LoginForm: View { | |
@StateObject var viewModel = LoginViewModel() | |
@FocusState private var focusedField: LoginViewModel.Field? | |
var body: some View { | |
Form { | |
TextField("Username", text: $viewModel.username) | |
.focused($focusedField, equals: .username) | |
SecureField("Password", text: $viewModel.password) | |
.focused($focusedField, equals: .password) | |
Button("Sign In") { | |
viewModel.signInButtonTapped() | |
} | |
} | |
.sync($viewModel.focusedField, $focusedField ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment