@FocusState

SwiftUI Junior Swift 5.5+ iOS 15+ Reviewed By Alok Singh

Fill the blank

Fill the blank so Next moves focus to the password field.

enum Field { case email, password }
@FocusState private var focus: Field?

TextField("Email", text: $email)
    .focused($focus, equals: .email)
SecureField("Password", text: $password)
    .focused($focus, equals: .password)
Button("Next") { ____ }
Options
Hint 1 of 1

Focus state is a value you assign.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A focus = .password

Correct. Assigning the focus state moves keyboard focus.

Why not the others?
  • B focus.toggle(). An optional enum can't be toggled.
  • C $focus = .password. $focus is a binding projection; you assign the wrapped value.
  • D passwordField.becomeFirstResponder(). That's UIKit; SwiftUI has no view reference to call.

30-second answer

@FocusState tracks which control has keyboard focus. Bind it to fields with .focused($focus, equals: .email), set it to move focus, and set it to nil to dismiss the keyboard. An optional enum covers forms with many fields.

Practise saying it · 30 s. No recording, just a timer

Explain @FocusState.

Say your answer out loud, then check which of these points you covered:

  • Tracks keyboard focus
  • focused(_:equals:)
  • nil dismisses the keyboard

Deep dive

Use .onSubmit with .submitLabel(.next) to move to the next field.

Setting focus in .onAppear may need a short delay inside sheets.

@FocusState private var isFocused: Bool works for a single field.

.defaultFocus sets the initial focus on iPadOS, macOS and tvOS.

Common mistakes

  • Using UIKit's becomeFirstResponder from SwiftUI.
  • Forgetting to set focus to nil to dismiss the keyboard.
  • Using a separate Bool per field.

Senior take & follow-ups

Seniors use an enum for multi-field forms and keep keyboard handling declarative.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you dismiss the keyboard?

    Show hint

    Set the focus state to nil.

  2. How do you validate on leaving a field?

    Show hint

    Use onChange of the focus state.

From the author

Catalog - UI

Made by the author: browse UIKit and SwiftUI components with live demos, and copy their code snippets into your project.

Suggest a fix if something here is wrong or out of date.