Keep Keyboard Focus Stable When SwiftUI Forms Reflow
A form can keep every character of a draft and still interrupt the person editing it. The fields rearrange, the keyboard disappears, or Next moves to the wrong row after a deletion.
The problem is often that the app identifies focus by a field’s current position. “The second field” is a fragile identity when fields can move. Give focus the same stable identity that belongs to the data, then make traversal a separate decision.
Give every field one focus identity
SwiftUI’s FocusState tracks focus through a Boolean or optional value. For a dynamic form, an optional field ID is useful: it identifies one field, and nil represents no focused field.
Do not bind the same ID to two different inputs. That makes a programmatic focus request ambiguous. Also avoid creating new UUIDs in body; a field’s identity should survive routine rendering and layout changes.
Our example uses an array of small contact fields. The parent owns the values and their IDs. A layout change changes arrangement, while the field collection and focus binding remain in the same view structure.
import SwiftUI
struct ContactField: Identifiable {
let id: UUID
var label: String
var value: String
}
func nextField(after current: UUID, in fields: [ContactField]) -> UUID? {
guard let index = fields.firstIndex(where: { $0.id == current }),
fields.indices.contains(index + 1)
else { return nil }
return fields[index + 1].id
}
func focusAfterRemoving(
_ removed: UUID, focused: UUID?, from fields: [ContactField]
) -> UUID? {
guard focused == removed else { return focused }
guard let index = fields.firstIndex(where: { $0.id == removed }) else { return nil }
if fields.indices.contains(index + 1) { return fields[index + 1].id }
if index > 0 { return fields[index - 1].id }
return nil
}
struct ContactFields: View {
@Binding var fields: [ContactField]
@Environment(\.dynamicTypeSize) private var typeSize
@Environment(\.horizontalSizeClass) private var widthClass
@FocusState private var focused: UUID?
var body: some View {
ScrollView {
layout {
ForEach($fields) { $field in
VStack(alignment: .leading, spacing: 8) {
TextField(field.label, text: $field.value)
.textFieldStyle(.roundedBorder)
.focused($focused, equals: field.id)
.submitLabel(
nextField(after: field.id, in: fields) == nil ? .done : .next
)
.onSubmit { focused = nextField(after: field.id, in: fields) }
Button("Remove \(field.label)", role: .destructive) {
let removedID = field.id
let replacement = focusAfterRemoving(
removedID, focused: focused, from: fields)
fields.removeAll { $0.id == removedID }
focused = replacement
}
}
}
}
.padding()
}
}
private var layout: AnyLayout {
let horizontal =
widthClass == .regular
&& !typeSize.isAccessibilitySize && fields.count <= 3
return horizontal
? AnyLayout(HStackLayout(alignment: .top, spacing: 20))
: AnyLayout(VStackLayout(alignment: .leading, spacing: 20))
}
}
Make Next follow the current model
nextField looks up the current ID and returns its successor in the current array. It does not retain an index captured when the form first appeared.
That distinction matters when the user reorders fields or a product rule inserts an extra field. The visual order and the Next policy should come from the same meaningful sequence. A missing current ID returns nil instead of accidentally advancing from a stale position.
The .submitLabel modifier describes the keyboard action; the .onSubmit handler supplies the behavior. At the final field, the binding becomes nil. A product might choose to submit the form instead, but that is a separate validation decision, not an automatic consequence of displaying Done.
These are single-line text fields. A multiline editor may need Return to insert a line break. Do not copy a “Return always advances” rule into a notes editor without considering its editing contract.
Decide where focus goes before removal
When the focused row is removed, this example prefers the following row, then the previous row, then no field. It computes that decision from the old collection before mutating it.
Removing an unrelated row preserves the current focus ID. Otherwise, clicking Remove on one field could unexpectedly send the keyboard to another field the person was not editing.
The local removedID is captured before deletion as well. A binding obtained while iterating a collection should not be consulted afterward as though the deleted element still occupied its old location.
This is one reasonable policy, not a universal rule. A form that removes a whole section may prefer its section heading or the next remaining section’s first input. Write that policy as a function and test it with the actual collection transitions.
Change arrangement without rebuilding the form
DynamicTypeSize.isAccessibilitySize identifies accessibility text sizes. This sample uses a vertical arrangement for those sizes, for compact width, and for more than three fields. Its horizontal arrangement is deliberately limited to a small group.
AnyLayout lets the container type change while retaining the child structure. That avoids duplicating the inputs into separate horizontal and vertical branches. The input values also remain in the parent’s model rather than being recreated by a layout-specific child.
The width class is a coarse choice for this example, not proof that every localized field fits. Measure the real labels and available space in your app. A narrow regular-width presentation may still need the vertical arrangement. Do not fix a cramped form by capping Dynamic Type or shrinking its text.
Stable IDs and structure remove common sources of focus loss; they do not prove every operating-system transition preserves the keyboard. That still needs interaction testing.
Keep keyboard traversal and VoiceOver order distinct
This article’s FocusState controls keyboard editing. It does not define the complete VoiceOver reading sequence, Switch Control scanning behavior, or hardware keyboard Tab order.
The previous form-validation article uses accessibility focus for a different purpose: explaining an invalid submission. Keep those responsibilities distinct so a layout refresh does not start issuing accessibility focus requests merely because keyboard focus exists.
The sample’s Remove buttons remain independent controls. A screen reader should be able to reach them and identify which field each affects. Combining every row into one accessibility element without checking its actions could hide those operations.
Test while something is actually focused
Start editing the middle field, then change text size and available width. Confirm the value survives and focus remains useful. Remove that field, remove a different field, and remove the final field. Check Next after reordering the model.
For a long form, also verify the requested destination is visible. A lazily created offscreen field introduces another lifecycle boundary: a focus request may arrive before that input exists. This sample uses ordinary stack layouts. If you move it into a lazy container, add deliberate scrolling and destination-readiness handling, then test that handoff instead of adding an unexplained timer.
September 2026 review: the full view type-checks for iOS 17 against the iOS 27 SDK with Swift 6.4. Executable policy checks passed for Next, missing IDs, focused-row removal, last-row removal, unrelated removal, and reordered fields. Actual keyboard retention, scrolling, and assistive-technology traversal have not been device-tested.
The useful invariant is simple: a field keeps its identity when its position changes. Once that is true, the app can make movement and deletion policies explicit instead of asking focus to guess what the new layout means.