简体   繁体   中英

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

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 (eg, 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:

在此处输入图像描述

and I'd like to get something like this instead: 在此处输入图像描述

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

演示

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)
    }
}

backup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM