Search code examples
swiftuitextfield

Expand padding around text inside border of TextField swiftUI control


I am working to get the below style in a swiftUI textfield (and secure version): enter image description here

The part that is troubling me is pushing out the border from the text in the control. When I do it standard it looks like this:

enter image description here

I could probably do something with an additional view but I think that I might be missing something easy to adjust the control.

TextField("Email Address", text: $emailAddress)
            .textFieldStyle(.roundedBorder)
            .keyboardType(.emailAddress)

Adding .padding() does this: enter image description here


Solution

  • You basically have 2 options.

    1. Use the plain TextFieldStyle and apply your own styling:
    TextField("Email address", text: $emailAddress)
        .textFieldStyle(.plain)
        .padding(16)
        .overlay {
            RoundedRectangle(cornerRadius: 5)
                .stroke(Color.blue, lineWidth: 2)
        }
        .padding(.horizontal, 16)
    
    1. Create your own TextFieldStyle so you can easily reuse the styling for other text fields:
    struct ContentView: View {
        @State var emailAddress: String = ""
        
        var body: some View {
            TextField("Email address", text: $emailAddress)
                .textFieldStyle(BlueTextFieldStyle())
                .padding(.horizontal, 16)
            
        }
    }
    
    #Preview {
        ContentView()
    }
    
    struct BlueTextFieldStyle: TextFieldStyle {
        func _body(configuration: TextField<Self._Label>) -> some View {
            configuration
                .padding(16)
                .overlay {
                    RoundedRectangle(cornerRadius: 5)
                        .stroke(Color.blue, lineWidth: 2)
                }
        }
    }
    

    Here's a good overview I've used in the past: https://thehappyprogrammer.com/custom-textfield-in-swiftui