How it works
DefaultFocusEvaluationPriority describes how strongly SwiftUI should honor a programmatic default-focus preference when a focus scope first appears. When you ask a view to receive focus by default, that request can compete with focus the system would otherwise assign on its own, and the priority value tells SwiftUI which one wins. Reach for it through the priority parameter of the defaultFocus(_:_:priority:) modifier when you need to control whether your stated default takes precedence over the system's automatic choice.
Bind focus state to drive the default
Default focus operates on a focus binding, so the value you prioritize must be tied to a
@FocusState. Here@FocusState private var focused: Booltracks whether the field is active, and.focused($focused)connects that state to theTextFieldso it can become the default focus target.Declare the default with defaultFocus(_:_:priority:)
The
defaultFocus($focused, true, priority:)modifier names the binding and the value it should take when the scope appears. The first two arguments say "makefocusedequaltrueby default," and the trailingpriority:parameter is whereDefaultFocusEvaluationPriorityenters to weight that request.Choose the evaluation priority
DefaultFocusEvaluationPrioritysupplies the constant passed topriority:. Using.userInitiatedsignals that this default reflects an explicit intent and should be favored over the focus SwiftUI might otherwise pick automatically, rather than yielding to the system's own default selection.Let the priority resolve focus on appearance
When the enclosing
VStackis first shown, SwiftUI evaluates the default-focus request and compares itsDefaultFocusEvaluationPriorityagainst any competing system default. With.userInitiated, the binding resolves totrue, theTextFieldbecomes first responder, and theText(focused ? "Editing" : "Tap to edit")label updates to reflect the active editing state.
priority: .userInitiated to priority: .automatic and relaunch to see how a lower-priority default lets the system's own focus choice take over instead of the field activating on appearance.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct DefaultFocusEvaluationPriorityDemo: View {
@FocusState private var focused: Bool
@State private var name = ""
var body: some View {
VStack(spacing: 16) {
Text("Default Focus")
.font(.headline)
TextField("Your name", text: $name)
.textFieldStyle(.roundedBorder)
.focused($focused)
Text(focused ? "Editing" : "Tap to edit")
.foregroundStyle(.secondary)
}
.padding()
.defaultFocus($focused, true, priority: .userInitiated)
}
}