In a SwiftUI checkout address form, how do you use @FocusState with an enum so the keyboard's Next key moves focus through the fields?
answer
- one property for all fields
- optional, because focus can be absent
- one case per field
- onSubmit assigns the next case
- nil closes the keyboard
basics
~20 sDeclare @FocusState var focus: Field? over a Hashable enum, mark each field with focused($focus, equals:), give them submitLabel(.next), and in one onSubmit assign the next case; setting nil on the last field dismisses the keyboard.
solid answer
~40 s`@FocusState` is a value SwiftUI updates as focus moves and that moves focus when you write it. With several fields you declare `@FocusState private var focus: Field?` over a `Hashable` enum; it must be optional (or a `Bool`) because focus can be absent, and the compiler rejects a non-optional enum. Each field gets `.focused($focus, equals: .street)` with its own case. `.submitLabel(.next)` only retitles the Return key, so a single `onSubmit` on the `Form` switches on `focus` and assigns the next case. The last field gets `.submitLabel(.done)` and sets `focus = nil`, which removes focus and dismisses the keyboard. Binding one case to two fields is ambiguous: SwiftUI picks the first and warns at runtime.
code
swift · 41 linesimport SwiftUI
struct ShippingAddressForm: View {
enum Field: Hashable { case name, street, city, postcode, phone }
@State private var address = ShippingAddress()
@FocusState private var focus: Field?
var body: some View {
Form {
TextField("Full name", text: $address.name)
.focused($focus, equals: .name)
.submitLabel(.next)
TextField("Street", text: $address.street)
.focused($focus, equals: .street)
.submitLabel(.next)
TextField("City", text: $address.city)
.focused($focus, equals: .city)
.submitLabel(.next)
TextField("Postcode", text: $address.postcode)
.focused($focus, equals: .postcode)
.submitLabel(.next)
TextField("Phone", text: $address.phone)
.focused($focus, equals: .phone)
.submitLabel(.done)
}
.onSubmit {
switch focus {
case .name: focus = .street
case .street: focus = .city
case .city: focus = .postcode
case .postcode: focus = .phone
case .phone, nil: focus = nil
}
}
}
}
struct ShippingAddress {
var name = "", street = "", city = "", postcode = "", phone = ""
}go deeper
Know that @FocusState plus focused(_:equals:) marks which field has the keyboard, and that setting it moves the cursor.
Explain why the value must be optional or Bool, how one onSubmit switches on the current case, and that submitLabel only retitles the Return key.
Catch the ambiguous duplicate case, number pads with no Return key, and fields that need submitScope; use focus to land users on the first invalid field.
Treat focus order as part of a form's accessibility and conversion design, and push teams toward one shared enum-and-onSubmit pattern rather than ad hoc focus code.
## What `@FocusState` is **`@FocusState`** is a SwiftUI property wrapper (iOS 15) whose value SwiftUI updates **as focus moves** within the scene, and which you can also **write** to move focus. For text entry, "focus" means which field owns the keyboard. Apple's documentation describes both directions: - When focus **enters** a view marked with `focused(_:equals:)`, the property becomes that view's value. - When focus **leaves**, the property resets to `nil` (or `false` for a Bool). - When **you set** the property to a view's value, focus moves to that view; setting `nil` or `false` removes focus from every bound field, which also **dismisses the keyboard**. A plain `@State` value cannot do this: SwiftUI never writes it when the user taps another field, and changing it moves nothing. ## Bool or optional enum `FocusState` has exactly two initializers: one where the value is `Bool` and one where it is an `Optional` of a `Hashable` type. The compiler enforces it: declaring `@FocusState var focus: Field` with a non-optional enum fails with "initializer 'init()' requires the types 'Field' and 'Bool' be equivalent". The reason is that focus can be **absent** from the whole view tree, and the value needs a way to say so. | Shape | Modifier | Use it for | |---|---|---| | `@FocusState var isFocused: Bool` | `focused(_:)` | One field, such as a single comment box | | `@FocusState var focus: Field?` | `focused(_:equals:)` | Several fields, one property tracking which is active | With five address fields, one optional enum is the clear choice: one property answers "which field is active?", and assigning a case moves the cursor there. ## Wiring the Next key The checkout address form has five fields and a Next key that walks down them: 1. Declare `enum Field: Hashable` with one case per field and `@FocusState private var focus: Field?`. 2. Mark each field with `.focused($focus, equals: .street)` and so on, **one case per field**. 3. Set `.submitLabel(.next)` on every field but the last, and `.submitLabel(.done)` on the last. The label only changes the Return key's title. 4. Attach a single `onSubmit` to the `Form`. Apple's documentation says the action can sit on an individual view or a whole hierarchy, so one closure can `switch` on `focus` and assign the next case. 5. On the last field, set `focus = nil` to drop focus and close the keyboard. ```swift import SwiftUI struct ShippingAddressForm: View { enum Field: Hashable { case name, street, city, postcode, phone } @State private var address = ShippingAddress() @FocusState private var focus: Field? var body: some View { Form { TextField("Full name", text: $address.name) .focused($focus, equals: .name) .submitLabel(.next) TextField("Street", text: $address.street) .focused($focus, equals: .street) .submitLabel(.next) TextField("City", text: $address.city) .focused($focus, equals: .city) .submitLabel(.next) TextField("Postcode", text: $address.postcode) .focused($focus, equals: .postcode) .submitLabel(.next) TextField("Phone", text: $address.phone) .focused($focus, equals: .phone) .submitLabel(.done) } .onSubmit { switch focus { case .name: focus = .street case .street: focus = .city case .city: focus = .postcode case .postcode: focus = .phone case .phone, nil: focus = nil } } } } struct ShippingAddress { var name = "", street = "", city = "", postcode = "", phone = "" } ``` ## What goes wrong - **The same case on two fields.** If two fields both use `.focused($focus, equals: .street)`, typing into either sets `.street`, but setting `.street` in code is ambiguous. Apple's documentation says SwiftUI picks the **first candidate** and emits a **runtime warning**. - **Expecting `submitLabel(.next)` to move focus.** It does not; without the `onSubmit` code, pressing Next never moves the cursor to the following field. - **A field that should not advance.** A field inside the form whose Return should not reach the form-level `onSubmit` can opt out with `submitScope()`. - **Number and phone pads.** On iPhone these keyboards have no Return key, so `onSubmit` cannot fire from them; give them a Next button another way, such as a keyboard toolbar. ## Beyond Next The same property drives validation flow: when the user taps Pay with the postcode empty, set `focus = .postcode` and the cursor lands in the field that needs fixing. Reading `focus` also tells a view which field is active, for example to highlight its row. For the field focus should start in, `defaultFocus(_:_:priority:)` (iOS 17) declares a preferred value; Apple's documentation says SwiftUI evaluates it when the window first appears and when a focus state update moves focus automatically.
- How do you send the user back to the first invalid field when they tap Pay?In the Pay button's action, check the fields in order and assign the first failing case, such as `focus = .postcode`. Writing a `@FocusState` value moves focus to the view marked with that value, so the keyboard opens on that field. Only when every field passes do you start the payment.
- When is a Bool @FocusState with focused(_:) the better choice?When one field is all you track, such as a single comment box you want to focus or dismiss. With several fields, several Bools can disagree and give no single answer to which field is active; one optional enum keeps that answer in one place and moves focus with one assignment.
- How do you keep a tags field inside the form from triggering the form-level onSubmit?Apply `submitScope()` to that field. Apple's documentation says it stops submission triggers from that view reaching `onSubmit` actions higher in the hierarchy, so Return in the tags field no longer advances focus or submits the form.
- submitLabel(.next) moves focus to the next field without any extra code
- A @FocusState property can be any Hashable enum, optional or not
- Binding two fields to the same focus case is fine; SwiftUI focuses both
- A plain @State variable can move focus if you change it
- Every keyboard has a Return key, so onSubmit always works for advancing