How to Add Borders to Views in SwiftUI
UIKit has a pretty straightforward way to add borders, but you first need to understand that a UIView has a layer, and that’s where you need to go to set a border. SwiftUI simplifies things further by promoting borders to a modifier directly on a View.
Adding a simple border
To add a simple border you just need to add the .border
modifier and give it a color.
Text("SwiftUI Borders")
.font(.largeTitle)
.border(Color.blue)
You can also customize the width of a border
Text("SwiftUI Borders")
.font(.largeTitle)
.border(Color.blue, width: 2)
That looks pretty ugly though, right? You probably don’t want your borders touching the edges if your View’s content like that. To fix it all you need to do is add some padding()
Text("SwiftUI Borders")
.font(.largeTitle)
.padding()
.border(Color.blue, width: 2)
Much better!
Rounding Corners
Things get a little bit more complicated when you want to round the corners of your borders. In order to get a rounded corner look you’ll need to use a shape, such as a Rectangle
. But since you want to make sure your Rectangle
is sized to match your View you’ll have to add it on top of your View. This can be done using an overlay:
Text("SwiftUI Borders")
.font(.largeTitle)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.blue, lineWidth: 2)
)
In the code above we’re taking the Text
View and adding an overlay
to it. Then within the overlay we’re adding a RoundedRectangle
shape, and giving that the border. But! As you can see you can’t add a border
to a shape like you would a regular View. Instead you need to use stroke
.
Using stroke
is better in my opinion because actually gives you way more control over your border. Let’s say you wanted to change the rounded border above to one that is dashed. And because your designer is super picky about dashed lines they want you to make sure the dashes are 10pts long, with 2pts between each dash. No problem!
Text("SwiftUI Borders")
.font(.largeTitle)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.blue, style: StrokeStyle(lineWidth: 2, dash: [10, 2]))
)
StrokeStyle
give you lots of options to play with. If you’re curious, you can read more about it in the Apple docs.
And that’s it!