Nicolas Gimelli
Nicolas Gimelli

Reputation: 1302

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?

Upvotes: 24

Views: 10771

Answers (1)

Yrb
Yrb

Reputation: 9665

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
        }
    }
  ...
}

Upvotes: 23

Related Questions