21
Aug
2021
Navigate Fields Using Keyboard in SwiftUI
Reading time: 1 min
This recipe shows how to navigate from one text field to another using keyboard buttons in SwiftUI by combining @FocusState
and onSubmit
.
The end result looks like this:
The recipe goes as following:
- Declare an enum that holds aliases for focusable fields. In the code below, that's
FormField
. - Declare a
@FocusField
property whose type is that enum. Make it nullable, so that you can dismiss the keyboard at any time. - Use the
focused
modifier on yourTextField
s. - Update the focused field property in form's
onSubmit
, which is called whenever the keyboard's submit button (the one at the far bottom right) is pressed.
struct ContentView: View {
@State private var firstName = ""
@State private var lastName = ""
@State private var phoneNumber = ""
@FocusState private var focusedField: FormField?
var body: some View {
Form {
TextField("First name", text: $firstName)
.disableAutocorrection(true)
.submitLabel(.next)
.focused($focusedField, equals: .firstName)
TextField("Last name", text: $lastName)
.textContentType(.familyName)
.disableAutocorrection(true)
.submitLabel(.next)
.focused($focusedField, equals: .lastName)
TextField("Phone number", text: $phoneNumber)
.textContentType(.telephoneNumber)
.submitLabel(.done)
.focused($focusedField, equals: .phoneNumber)
}
.onSubmit {
switch focusedField {
case .firstName:
focusedField = .lastName
case .lastName:
focusedField = .phoneNumber
default:
focusedField = nil
}
}
}
enum FormField {
case firstName, lastName, phoneNumber
}
}