History
Loading...
Loading...
September 28, 2025
@FocusState with enum cases to create seamless form field navigation. Define an enum for your fields and use .focused($focusedField, equals: .fieldName) to control focus programmatically, enabling 'Next' button functionality on the keyboard toolbar.This pattern uses @FocusState with an enum to manage keyboard focus across multiple form fields. The enum conforming to CaseIterable enables automatic field navigation, while the onSubmit modifier handles the transition logic between fields.
struct SmartFormView: View {
@State private var username = ""
@State private var email = ""
@State private var password = ""
@FocusState private var focusedField: FormField?
enum FormField: CaseIterable {
case username, email, password
}
var body: some View {
Form {
TextField("Username", text: $username)
.focused($focusedField, equals: .username)
.submitLabel(.next)
TextField("Email", text: $email)
.focused($focusedField, equals: .email)
.keyboardType(.emailAddress)
.submitLabel(.next)
SecureField("Password", text: $password)
.focused($focusedField, equals: .password)
.submitLabel(.done)
}
.onSubmit {
focusNextField()
}
}
private func focusNextField() {
guard let currentField = focusedField,
let currentIndex = FormField.allCases.firstIndex(of: currentField),
currentIndex < FormField.allCases.count - 1 else {
focusedField = nil // Dismiss keyboard on last field
return
}
focusedField = FormField.allCases[currentIndex + 1]
}
}Using an enum instead of individual @FocusState booleans provides type safety, makes the navigation logic scalable, and ensures consistent behavior. The CaseIterable conformance allows for generic navigation logic that works regardless of the number of fields, reducing maintenance overhead and potential bugs.