Creating borders around Views in SwiftUI is simple. But what if you wanted to create a stroked border? Let's see how to do that!

Let's replicate a button on the screenshot below.

In the end the code is pretty short and sweet.

import SwiftUI

struct ContentView: View {
    var body: some View {
        Button(action: { print("Yay!" )}) {
            HStack(spacing: 4) {
                Image(systemName: "plus.circle")
                Text("Add item")
            }
        }
        .foregroundColor(.green)
        .padding(12)
        .overlay(
            RoundedRectangle(cornerRadius: 8)
                .strokeBorder(
                    style: StrokeStyle(
                        lineWidth: 2,
                        dash: [15]
                    )
                )
                .foregroundColor(.green)
        )
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

The key part here is the overlay modifier. This modifier lets you put a shape as an overlay of your view.

Since I wanted my button to be rectangular with rounded corners, I used the RoundedRectangle shape. You could of course use any of the shapes Apple provides.

To get the dashed border we simply need to call the strokeBorder modifier which lets us define style of the overlay's stroke. Feel free to play with the parameters to get a different line!

Last thing not to be forgotten is the foregroundColor modifier. The foreground color defines the color of the shape as well as of its border.

That's it! With just a couple of lines of code we can have a nice dashed border around our view.