Created
November 1, 2021 17:45
-
-
Save appfrosch/a41960d9bb1caab91eebb17252e0621a to your computer and use it in GitHub Desktop.
Controlling the focus on textfields
This file contains hidden or 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
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