Skip to content

Instantly share code, notes, and snippets.

@disc0infern0
Created October 30, 2021 10:45
Show Gist options
  • Save disc0infern0/1246af4f52c2dad1d68ad8fcfc744414 to your computer and use it in GitHub Desktop.
Save disc0infern0/1246af4f52c2dad1d68ad8fcfc744414 to your computer and use it in GitHub Desktop.
Login form demonstrating change of focus using a view model
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