< 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 Build a functional Twitter clone using APIs and SwiftUI with Stream's 7-part tutorial series. In just four days, learn how to create your own Twitter using Stream Chat, Algolia, 100ms, Mux, and RevenueCat.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.