Expand padding around text inside border of TextField swiftUI control - Stack Overflow

admin2025-04-17  3

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

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:

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:

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

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:

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:

Share Improve this question edited Jan 30 at 21:08 Rob Bonner asked Jan 30 at 18:18 Rob BonnerRob Bonner 9,4168 gold badges36 silver badges57 bronze badges 3
  • 1 Please share a reproducible code of what you tried to achieve this, so it can be used as a basis for a possible solution. – Andrei G. Commented Jan 30 at 19:03
  • Have you tried .padding() to "push out the border" before applying a background modifier? – Stoic Commented Jan 30 at 20:14
  • Tried .padding(), this just moves the control over and down. – Rob Bonner Commented Jan 30 at 21:09
Add a comment  | 

1 Answer 1

Reset to default 1

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

转载请注明原文地址:http://anycun.com/QandA/1744898762a89190.html