< How to dismiss the keyboard for a TextField | How to make a TextField expand vertically as the user types > |
Updated for Xcode 14.2
SwiftUI on macOS provides a defaultFocus()
modifier that lets us activate one view as the first responder to user input as soon as a view is shown. Sadly it doesn’t exist on iOS, but we can work around that using onAppear()
.
First, here’s the code with the workaround in place, suitable for use on iOS:
struct ContentView: View {
enum FocusedField {
case firstName, lastName
}
@State private var firstName = ""
@State private var lastName = ""
@FocusState private var focusedField: FocusedField?
var body: some View {
Form {
TextField("First name", text: $firstName)
.focused($focusedField, equals: .firstName)
TextField("Last name", text: $lastName)
.focused($focusedField, equals: .lastName)
}
.onAppear {
focusedField = .firstName
}
}
}
Download this as an Xcode project
And here’s the code using defaultFocus()
, suitable for use on macOS:
struct ContentView: View {
enum FocusedField {
case firstName, lastName
}
@State private var firstName = ""
@State private var lastName = ""
@FocusState private var focusedField: FocusedField?
var body: some View {
Form {
TextField("First name", text: $firstName)
.focused($focusedField, equals: .firstName)
TextField("Last name", text: $lastName)
.focused($focusedField, equals: .lastName)
}
.defaultFocus($focusedField, .firstName)
}
}
Hopefully defaultFocus()
comes to iOS in a future update!
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.