Search code examples
swifttextfieldswiftuifirst-responder

SwiftUI: How to make TextField become first responder?


Here's my SwiftUI code:

struct ContentView : View {

    @State var showingTextField = false
    @State var text = ""

    var body: some View {
        return VStack {
            if showingTextField {
                TextField($text)
            }
            Button(action: { self.showingTextField.toggle() }) {
                Text ("Show")
            }
        }
    }
}

What I want is when the text field becomes visible, to make the text field become the first responder (i.e. receive focus & have the keyboard pop up).


Solution

  • iOS 15.0+

    macOS 12.0+,

    Mac Catalyst 15.0+,

    tvOS 15.0+,

    watchOS 8.0+

    Use focused(_:) if you have a single TextField.

    focused(_:)

    Modifies this view by binding its focus state to the given Boolean state value.

    struct NameForm: View {
        
        @FocusState private var isFocused: Bool
        
        @State private var name = ""
        
        var body: some View {
            TextField("Name", text: $name)
                .focused($isFocused)
            
            Button("Submit") {
                if name.isEmpty {
                    isFocued = true
                }
            }
        }
    }
    
    

    Use focused(_:equals:) should you have multiple TextFields.

    focused(_:equals:)

    Modifies this view by binding its focus state to the given state value.

    struct LoginForm: View {
        enum Field: Hashable {
            case usernameField
            case passwordField
        }
    
        @State private var username = ""
        @State private var password = ""
        @FocusState private var focusedField: Field?
    
        var body: some View {
            Form {
                TextField("Username", text: $username)
                    .focused($focusedField, equals: .usernameField)
    
                SecureField("Password", text: $password)
                    .focused($focusedField, equals: .passwordField)
    
                Button("Sign In") {
                    if username.isEmpty {
                        focusedField = .usernameField
                    } else if password.isEmpty {
                        focusedField = .passwordField
                    } else {
                        handleLogin(username, password)
                    }
                }
            }
        }
    }
    

    SwiftUI Documentation


    Update

    I tested this in Xcode version 13.0 beta 5 (13A5212g). It works