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:

preview

The recipe goes as following:

  1. Declare an enum that holds aliases for focusable fields. In the code below, that's FormField.
  2. Declare a @FocusField property whose type is that enum. Make it nullable, so that you can dismiss the keyboard at any time.
  3. Use the focused modifier on your TextFields.
  4. 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
  }
}

Next Post Previous Post