Fix: TextField Not Becoming First Responder When Shown in SwiftUI

Fix: TextField Not Becoming First Responder When Shown in SwiftUI

Written by

in

Quick answer: Use @FocusState with the focused(_:) modifier to programmatically control TextField focus. Set the focus state to true when the TextField becomes visible to make it the first responder and show the keyboard automatically.

Why this happens

SwiftUI’s declarative nature means views don’t have direct access to UIKit’s becomeFirstResponder() method. Before iOS 15, developers had to use workarounds like UITextField introspection or UIViewRepresentable wrappers to programmatically show the keyboard. The framework didn’t expose a native way to request focus for a TextField when it appears conditionally or after a user action.

Apple introduced @FocusState and the focused(_:) / focused(_:equals:) modifiers in iOS 15, macOS 12, tvOS 15, and watchOS 8. These APIs bind a view’s focus state to a Boolean or enum value, letting you drive focus programmatically without dropping into UIKit.

How to fix it

1. Single TextField — use @FocusState with focused(_:)

For a single field, declare a @FocusState Boolean and bind it to the TextField. Toggle the Boolean when you want the field to gain focus.

import SwiftUI

struct ContentView: View {
    @State private var showingTextField = false
    @State private var text = ""
    @FocusState private var isFieldFocused: Bool

    var body: some View {
        VStack {
            if showingTextField {
                TextField("Enter text", text: $text)
                    .focused($isFieldFocused)
                    .textFieldStyle(.roundedBorder)
                    .padding()
            }

            Button(showingTextField ? "Hide" : "Show") {
                withAnimation {
                    showingTextField.toggle()
                }
                // Focus after the view appears
                if showingTextField {
                    DispatchQueue.main.async {
                        isFieldFocused = true
                    }
                }
            }
            .buttonStyle(.borderedProminent)
        }
    }
}

Key points:
– Wrap the focus change in DispatchQueue.main.async (or use .onAppear on the TextField) so the view is in the hierarchy before requesting focus.
– The focused(_:) modifier takes a Binding<Bool>. Setting it to true makes the field first responder; false resigns it.

2. Multiple TextFields — use @FocusState with an enum and focused(_:equals:)

When you have several fields, use a Hashable enum to identify each one. Bind the same @FocusState property to each field with equals:.

struct LoginForm: View {
    enum Field: Hashable {
        case username
        case password
    }

    @State private var username = ""
    @State private var password = ""
    @FocusState private var focusedField: Field?

    var body: some View {
        Form {
            TextField("Username", text: $username)
                .focused($focusedField, equals: .username)
                .textContentType(.username)

            SecureField("Password", text: $password)
                .focused($focusedField, equals: .password)
                .textContentType(.password)

            Button("Sign In") {
                if username.isEmpty {
                    focusedField = .username
                } else if password.isEmpty {
                    focusedField = .password
                } else {
                    // perform login
                }
            }
            .disabled(username.isEmpty || password.isEmpty)
        }
    }
}

When to use this:
– Login / registration forms
– Multi-step onboarding flows
– Any screen where you need to move focus between fields programmatically

3. Focus on appear without a button trigger

If the TextField is already visible when the view loads, use .onAppear on the field itself:

TextField("Search", text: $query)
    .focused($isFocused)
    .onAppear {
        isFocused = true
    }

For conditionally shown fields, combine the visibility toggle with a delayed focus request as shown in the first example.

4. Legacy workaround (iOS 14 and earlier) — SwiftUI-Introspect

If you must support iOS 14, the SwiftUI-Introspect package exposes the underlying UITextField:

// Requires: import Introspect
TextField("", text: $value)
    .introspectTextField { textField in
        textField.becomeFirstResponder()
    }

Note: This approach relies on private view hierarchy traversal and may break across OS updates. Prefer the native @FocusState API on supported versions.

How to prevent it

  • Adopt @FocusState as the single source of truth for focus in new SwiftUI code.
  • Avoid mixing UITextField introspection with @FocusState on the same field — they fight for first-responder status.
  • Test focus behavior on device, not just the simulator, because hardware keyboards and external displays affect first-responder logic.
  • Use textContentType on fields so the system can offer appropriate autofill and keyboard types.

FAQ

Does @FocusState work on macOS and tvOS?

Yes. The API is available on macOS 12+, tvOS 15+, and watchOS 8+. On macOS, focus follows the standard window key-view loop; on tvOS it integrates with the focus engine for Siri Remote navigation.

Can I animate the keyboard appearance when setting focus?

The keyboard animation is system-controlled. Wrapping the focus change in withAnimation animates your view hierarchy changes (like the conditional if showingTextField), but the keyboard slide-up follows its own timing.

Why does the keyboard dismiss when I push a new navigation view?

Pushing a new view often resigns first responder as part of the transition. If you need the field to stay focused, consider keeping the field in the same view hierarchy or re-requesting focus in the new view’s .onAppear.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.