How to add borders to SwiftUI views

Learn how to add borders to SwiftUI views including: Text view, Stack view, Image view, and Button. Create rectangular or rounded-corners borders using .border() or .overlay() modifiers respectively. Create solid line or dashed borders.

Add default, rectangular border to a Text view using .border() modifier:

Text("SwiftUI Tutorials")
    .font(.largeTitle)
    .padding()
    .border(Color.black)
Border around Text view in SwiftUI
Border around Text view in SwiftUI

Add rectangular border to a Text view with custom width:

Text("SwiftUI Tutorials")
    .font(.largeTitle)
    .padding()
    .border(Color.black, width: 5)
Rectangular border around Text view with custom width
Rectangular border around Text view with custom width

Add rounded border to a Text view using .overlay() modifier and RoundedRectangle shape with a custom stroke width:

Text("SwiftUI Tutorials")
    .font(.largeTitle)
    .padding()
    .overlay(
        RoundedRectangle(cornerRadius: 15)
        .stroke(lineWidth: 2)
    )
Rounded border around Text view in SwiftUI
Rounded border around Text view in SwiftUI

A default, rectangular border can be added to a stack view using the .border() modifier:

VStack {
    Text("Simple Swift Guide")
        .font(.largeTitle)
    Text("SwiftUI Tutorials")
        .font(.title)
        .foregroundColor(.gray)
}.padding()
.border(Color.black, width: 4)
Rectangular border around Stack view in SwiftUI
Rectangular border around Stack view in SwiftUI

Remember that in order to add a border with rounded corners to a stack view, you need to use the method with .overlay() modifier.

Add border to a Button:

Button(action: {
    print("Button action")
}) {
    Text("Button label")
        .padding(10.0)
        .overlay(
            RoundedRectangle(cornerRadius: 10.0)
                .stroke(lineWidth: 2.0)
        )
}
Rounded border around Button in SwiftUI
Rounded border around Button in SwiftUI

Add border to an Image:

Image(systemName: "power")
    .font(.system(size: 56.0))
    .padding()
    .overlay(
        RoundedRectangle(cornerRadius: 10.0)
            .stroke(lineWidth: 2.0)
    )
Border around Image in SwiftUI
Border around Image in SwiftUI

Add a dashed border to a Text view using StrokeStyle() to define the stroke characteristics:

Text("SwiftUI Tutorials")
    .font(.largeTitle)
    .padding()
    .overlay(
        RoundedRectangle(cornerRadius: 15)
            .stroke(style: StrokeStyle(lineWidth: 4, dash: [15.0]))
    )
Dashed border around Text view in SwiftUI
Dashed border around Text view in SwiftUI

Related tutorials: