2

I am working on a SwiftUI project where I need a view to have a border with only some of the corners rounded (for instance, the top left and top right).

I added a RoundedRectangle with a stroke and was able to have all of the corners rounded. However, I need only some of the corners to be rounded and I couldn't figure out a way to do that.

This is the code I had to add a RoundedRectangle:

.overlay(
    RoundedRectangle(cornerRadius: 20)
       .stroke(Color.gray, lineWidth: 1)
)

To make only specific corners rounded, I looked at this Stackoverflow post: Round Specific Corners SwiftUI. However, I would have to get rid of the Rounded Rectangle (because it rounds all corners). I would have to use a normal border instead. But, with a normal border, it will cut out a piece of the border when rounding corners and trying any of the answers provided.

This is what I would ideally want it to look like (this is from an example from Bootstrap - we are rebuilding a website as an app): Picture

Thank you!

Rosalie W
  • 359
  • 4
  • 16

1 Answers1

1

Here's an alternative / easier way to recreate this. Add a white background to each of the rows and add a single gray background color behind them. Add spacing between the rows to let the gray background color appear like a divider between them. Then just add a rectangle overlay to the entire view, like you already had in your code!

struct CornerView: View {
    var body: some View {
        VStack(spacing: 1) {
            ForEach(0..<5) { index in
                Text("Item \(index)")
                    .frame(maxWidth: .infinity)
                    .frame(height: 55)
                    .background(Color.white)
            }
        }
        .background(Color.gray)
        .overlay(
            RoundedRectangle(cornerRadius: 5)
                .stroke(Color.gray, lineWidth: 1)
        )
        .padding()
    }
}

struct CornerView_Previews: PreviewProvider {
    static var previews: some View {
        CornerView2()
    }
}
nicksarno
  • 3,850
  • 1
  • 13
  • 33