History
Loading...
Loading...
September 1, 2025
@FocusState with enum values to manage focus across multiple text fields programmatically. Instead of boolean values, define an enum case for each focusable field: @FocusState private var focusedField: Field? where Field is an enum with cases like .email, .password, .confirmPassword.This practice creates a seamless user experience by automatically advancing focus between form fields and providing appropriate keyboard types for each input type.
struct LoginForm: View {
@State private var email = ""
@State private var password = ""
@FocusState private var focusedField: Field?
enum Field: CaseIterable {
case email, password
}
var body: some View {
VStack(spacing: 16) {
TextField("Email", text: $email)
.focused($focusedField, equals: .email)
.textContentType(.emailAddress)
.keyboardType(.emailAddress)
.onSubmit { focusedField = .password }
SecureField("Password", text: $password)
.focused($focusedField, equals: .password)
.textContentType(.password)
.onSubmit { submitForm() }
}
.onAppear { focusedField = .email }
}
private func submitForm() {
focusedField = nil
// Handle form submission
}
}Proper focus management reduces user friction, improves accessibility, and creates a more polished app experience. By using enums instead of multiple boolean states, the code is more maintainable and less prone to focus conflicts.