Skip to content

Instantly share code, notes, and snippets.

@appfrosch
Created November 1, 2021 17:45
Show Gist options
  • Save appfrosch/a41960d9bb1caab91eebb17252e0621a to your computer and use it in GitHub Desktop.
Save appfrosch/a41960d9bb1caab91eebb17252e0621a to your computer and use it in GitHub Desktop.
Controlling the focus on textfields
struct FocusView: View {
enum FocusField {
case username, password
}
@State private var username = ""
@State private var password = ""
@FocusState private var focusedField: FocusField?
var body: some View {
Form {
TextField("Username", text: $username)
.focused($focusedField, equals: .username)
.task {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { //this hack might be needed if the focus does not work on appear
focusedField = .username
}
}
TextField("Password", text: $password)
.focused($focusedField, equals: .password)
}
.onSubmit {
switch focusedField {
case .username:
focusedField = .password
case .password:
focusedField = .username
default:
break
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment