How to make a TextField or TextEditor have default focus
About 2 min
How to make a TextField or TextEditor have default focus 관련
SwiftUI by Example
Back to Home
How to make a TextField or TextEditor have default focus | SwiftUI by Example
How to make a TextField or TextEditor have default focus
Updated for Xcode 15
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
}
}
}
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!
Similar solutions…
How to customize the submit button for TextField, SecureField, and TextEditor | SwiftUI by Example
How to customize the submit button for TextField, SecureField, and TextEditor
How to create multi-line editable text with TextEditor | SwiftUI by Example
How to create multi-line editable text with TextEditor
How to change the background color of List, TextEditor, and more | SwiftUI by Example
How to change the background color of List, TextEditor, and more
How to make a TextField expand vertically as the user types | SwiftUI by Example
How to make a TextField expand vertically as the user types
How to make TextField uppercase or lowercase using textCase() | SwiftUI by Example
How to make TextField uppercase or lowercase using textCase()