SwiftUI TextField touchable Area

This solution only requires a @FocusState and an onTapGesture and a .background with color, and allows the user to tap anywhere, including the padded area, to focus the field. Tested with iOS 15.

struct MyView: View {
    @Binding var text: String
    @FocusState private var isFocused: Bool
    var body: some View {
        TextField("", text: $text)
            .padding()
            .background(Color.gray)
            .focused($isFocused)
            .onTapGesture {
                isFocused = true
            }
    }
}

Bonus:

If you find yourself doing this on several text fields, making a custom TextFieldStyle will make things easier:

struct TappableTextFieldStyle: TextFieldStyle {
    @FocusState private var textFieldFocused: Bool
    func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
            .padding()
            .background(Color.gray)
            .focused($textFieldFocused)
            .onTapGesture {
                textFieldFocused = true
            }
    }
}

Then apply it to your text fields with:

TextField("", text: $text)
    .textFieldStyle(TappableTextFieldStyle())

Leave a Comment