How can I programmatically have focus in a SwiftUI TextField at launch/load

I thought the following code would allow me to have focus in the TextField when the app loads. Is there something else/different that I need to do?

struct ContentView: View {
    enum FocusField {
        case password
    }
    @State var fieldContent: String = ""
    @FocusState var focus: FocusField?
    var body: some View {
        VStack {
            TextField("Enter text here", text: $fieldContent)
                .focused($focus, equals: .password)
            Text("Hello, world!")
        }
        .padding()
        .defaultFocus($focus, .password)
    }
}
Answered by DTS Engineer in 809532022

@mikeTheDad I was able to reproduce this as well. It looks like a bug to me on iOS.

Please file a bug report using Feedback Assistant and post the Feedback ID number here for reference.

You could try setting the focus value within the onAppear modifier closure. For example:

struct ContentView: View {
    @State var fieldContent: String = ""
    @FocusState var focus: FocusField?
    
    enum FocusField {
        case password
    }
   
    var body: some View {
        VStack {
            TextField("Enter text here", text: $fieldContent)
                .focused($focus, equals: .password)
            Text("Hello, world!")
        }
        .onAppear {
            self.focus = .password
        }
    }
}

@mikeTheDad I was able to reproduce this as well. It looks like a bug to me on iOS.

Please file a bug report using Feedback Assistant and post the Feedback ID number here for reference.

You could try setting the focus value within the onAppear modifier closure. For example:

struct ContentView: View {
    @State var fieldContent: String = ""
    @FocusState var focus: FocusField?
    
    enum FocusField {
        case password
    }
   
    var body: some View {
        VStack {
            TextField("Enter text here", text: $fieldContent)
                .focused($focus, equals: .password)
            Text("Hello, world!")
        }
        .onAppear {
            self.focus = .password
        }
    }
}
How can I programmatically have focus in a SwiftUI TextField at launch/load
 
 
Q