With the introduction of FocusState in SwiftUI, developers now have a powerful tool for managing the focus of text fields and other user input controls. FocusState allows you to programmatically control which field is active and respond to changes in focus. This feature is especially useful in forms, multi-field input screens, and complex UI workflows that rely on precise user interactions.
struct ContentView: View {
    
    @State var textInput: String = ""
    @FocusState var isTextFieldFocused: Bool
    
    var body: some View {
        VStack {
            TextField("Enter your name", text: $textInput)
                .padding()
                .focused($isTextFieldFocused)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            
            Button("Toggle Focus") {
                isTextFieldFocused.toggle()
            }
        }
        .padding()
    }
}
Using Multiple Fields
    In forms with multiple input fields, FocusState can help manage the focus of each field, allowing you to control which field is active based on the user’s actions.
    For instance, in a form with several text fields, you can define an enum to represent each field, then bind FocusState to that enum:
import SwiftUI
struct ContentView: View {
    enum Field: Hashable {
        case username
        case email
        case password
    }
    @State private var username: String = ""
    @State private var email: String = ""
    @State private var password: String = ""
    @FocusState private var focusedField: Field?
    var body: some View {
        VStack {
            TextField("Username", text: $username)
                .padding()
                .focused($focusedField, equals: .username)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            TextField("Email", text: $email)
                .padding()
                .focused($focusedField, equals: .email)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            SecureField("Password", text: $password)
                .padding()
                .focused($focusedField, equals: .password)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            Button("Next Field") {
                switch focusedField {
                case .username:
                    focusedField = .email
                case .email:
                    focusedField = .password
                default:
                    focusedField = nil
                }
            }
        }
        .padding()
    }
}
#Preview {
    ContentView()
}
  
Be the first to comment