I have trouble using cornerradius and borders on a textfield in SwiftUI

20.8k Views Asked by At

I have a text field in swiftUI, and in order to make it more appealing I'd like to add a border and have rounded corners. But it doesn't seem to work like it's supposed to (see image). What did I miss?

image 1

I've tried putting .cornerradius() before .border(), but it had the same effect.

TextField("Text input goes here", text: $addMins)
    .padding(.all, 5.0)
    .background(View)
    .frame(width: 300.0, height: 35.0)
    .border(Color.green, width: 2)
    .cornerRadius(14)
4

There are 4 best solutions below

2
On BEST ANSWER

So you want something like this?

TextField("Text Field", text: $text)
    .padding(4)
    .overlay(
        RoundedRectangle(cornerRadius: 14)
            .stroke(Color.green, lineWidth: 2)
    )
    .padding()

textfield with green rounded border

0
On

Here a simple way:


enter image description here


struct ContentView: View {
    
    @State private var stringOfTextField: String = String()

    var body: some View {
        
        TextField("Enter text . . .", text: $stringOfTextField)
            .padding()
            .overlay(RoundedRectangle(cornerRadius: 10.0).strokeBorder(Color.black, style: StrokeStyle(lineWidth: 1.0)))
            .padding()

    }
}
1
On

By the way, if you need a stroked and corner radiused text field with a different background, here's a solution

TextField("Placeholder", text: $text)
    .padding()
    .background(RoundedRectangle(cornerRadius: 5).fill(Color.gray))
    .overlay(
        RoundedRectangle(cornerRadius: 5)
            .stroke(lineWidth: 1)
    )
    .foregroundColor(.black)
1
On

There is now a very easy built in way to do this with the modifier: .textFieldStyle(.roundedBorder)