TIL: Border with Corner Radius in SwiftUI
Last updated: Sat Jun 10 2023
How do you add a colored border with a corner radius to a view in SwiftUI?
This is… surprisingly difficult, given in CSS it’s simply a matter of border-color
and border-radius
.
You might assume you can just combine the .border
and .cornerRadius
view modifers like so:
var body: some View {
Text("Sample Text")
.border(.black)
.cornerRadius(20)
}
That does not work, because the corner radius will mask the border, so the border will simply be cut off at the edges.
Also, apparently .cornerRadius
is deprecated as of iOS 17.
Instead, the best way seems to be to use the .overlay
view modifier:
var body: some View {
Text("Sample Text")
.overlay(RoundedRectangle(cornerRadius: 20).stroke(.gray))
}
References
- “How to draw a border around a view”, Hacking With Swift