Berry Blue
Berry Blue

Reputation: 16544

How to set the focus of a TextField when it appears on the view in SwiftUI

I want a text field to be selected when it appears on the screen, but I can't get it working. It only works in this example when I tap the button.

struct ContentView: View {
    @State var text = "Hello World"
    @FocusState var focused: Bool?
    var body: some View {
        VStack {
            TextField("Placeholder", text: $text)
                .focused($focused, equals: true)
                .onAppear {
                    focused = true
                }
            
            Button {
                focused = true
            } label: {
                Text("Select")
            }
        }
    }
}

Upvotes: 6

Views: 7967

Answers (1)

AdR
AdR

Reputation: 882

Execute focused = true after delay, using asyncAfter(). Try like this:

struct ContentView: View {
@State var text = "Hello World"
@FocusState var focused: Bool?
var body: some View {
    VStack {
        TextField("Placeholder", text: $text)
            .focused($focused, equals: true)
            .onAppear {
              DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
                self.focused = true
              }
            }
        
        Button {
            focused = true
        } label: {
            Text("Select")
        }
    }
    
}
}

Upvotes: 11

Related Questions