Reputation: 16544
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
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