SwiftUI view with rounded corners AND border

Viewed 1649
            ZStack {
                VStack {
                    Text("some text")
                    Button("Ok") {}
                     .foregroundColor(.cyan)
                     .padding()
                }
                .padding()
            }
            .background(.red)
            .border(.blue, width: 5)
            .cornerRadius(20)

enter image description here

I want the entire view to have the blue border with rounded corners (instead of the red square overlapping the rounded blue border. How? I've tried seemingly all variations of ordering the modifiers.

1 Answers

SwiftUI borders have straight edges no matter what corner radius you apply (.cornerRadius simply clips the view to a rounded mask and doesn't adjust the border's appearance).

If you want a rounded border, you'll need to overlay and .stroke a rounded rectangle:

VStack {
    Text("some text")
    Button("Ok") {}
        .foregroundColor(.cyan)
        .padding()
}
.padding()
.background(.red)
.cornerRadius(20) /// make the background rounded
.overlay( /// apply a rounded border
    RoundedRectangle(cornerRadius: 20)
        .stroke(.blue, lineWidth: 5)
)

Result:

Rounded blue border

Related