TextField.preferesDefaultFocus does not work in alerts

Hi,

I am having trouble setting default focus on a TextField that is inside of an alert. I expected TextField to receive default focus when alert is presented but result is that TextField does not receive default focus. This is happening on macOS 15.2, Swift (SwiftUI), Xcode 16.2 but hasn't worked on previous versions as well.

Example:

ContentView().alert("Sample Alert", isPresented: $present) {
    AlertView()
} message: {
    Text("Sample alert message.")
}

struct AlertView: View {
    @Namespace private var namespace
    @Environment(\.dismiss) private var dismiss
    @State private var text = ""

    var body: some View {
        VStack {
            TextField(text: $text, prompt: Text("Enter text")) {}
                .onSubmit {
                    var _ = print(text)
                    dismiss()
                }
                .autocorrectionDisabled()
                .lineLimit(1)
                .prefersDefaultFocus(in: namespace)

            Button("OK") {
                dismiss()
            }

            Button("Cancel", role: .cancel) {
                dismiss()
            }
        }
        .focusScope(namespace)
    }
}

I wasn’t able to reproduce this on macOS Sequoia 15.3 Beta 2 and 15.2. Also, since it’s a single TextField, it should receive focus without you needing to specify the default focus.

However, I noticed the issue if you have more than one TextField views present.

I would suggest you file a bug report via feedback assistant regardless and post the Feedback ID number here so we can follow up on that.

TextField.preferesDefaultFocus does not work in alerts
 
 
Q