How do I create a leading border for a view with cornerRadius in SwiftUI?

Viewed 598

So I've got a view

VStack(alignment: .leading) {
    Text("Top text").font(.title2).bold()
    Spacer()
    Text("Bottom text")
}
.padding()
.background(Color.white)
.cornerRadius(10)
.shadow(radius: 5)

and want to setup a left colored (e.g., in red) border that should match its rounded contour.

I tried adding:

.overlay(RoundedRectangle(cornerRadius: 20)
        .frame(width: 2, height: nil, alignment: .leading), alignment: .leading)

that does draw a left border but it doesn't match a rounded contour:

enter image description here

and I'd like to get something like this instead: enter image description here

1 Answers

Here is a demo of possible approach - using mask in overlay (also shown how to make button clickable if there will be some in card)

Tested with Xcode 12.1 / iOS 14.1

demo

struct DemoView: View {
    var body: some View {
        VStack(alignment: .leading) {
             Text("Top text").font(.title2).bold()
             Spacer()
             Button("Bottom text") {}
        }
        .padding()
        .background(Color.white)
        .cornerRadius(10)
        .shadow(radius: 5)
        .overlay(
          RoundedRectangle(cornerRadius: 10).fill(Color.red).mask(    // << here !!
            HStack {
                Rectangle().frame(width: 10)
                Spacer()
            }
        ).allowsHitTesting(false))   // << make click-through
        .frame(height: 200)
    }
}
Related