Search code examples
swiftuikeyboardtextfield

SwiftUI - How to activate TextField automatically when view loads?


I have a TextField in a view that looks something like this:

@FocusState private var keyboardFocused: Bool

VStack {
  TextField("Name your item...", text: $itemName)
    .focused($keyboardFocused)
  
  ...
}

Now, this is all embedded in a view that loads when a button is pressed, like this:

Button(action: someAction, label: { ... })
.fullScreenCover(isPresented: $viewIsPresented) {
  ViewWithTextField(...)
}

I want to make it so that when this view loads, the TextField is automatically activated/(focused?) and the keyboard pops up. How can I accomplish this?


Solution

  • Simply set your @FocusState to true in .onAppear and wrap it in a DispatchQueue.main.asyncAfter. The delay is needed because the view has to be on screen before the @FocusState is changed or it won't work.

    VStack {
      TextField("Name your item...", text: $itemName)
        .focused($keyboardFocused)
        .onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                keyboardFocused = true
            }
        }
      ...
    }