Chapter 51
Using UnevenRoundedRectangle to Round Specific Corners

In SwiftUI, there is a convenient built-in modifier called cornerRadius that allows you to easily create rounded corners for a view. By applying the cornerRadius modifier to a Rectangle view, you can transform it into a rounded rectangle. The value you provide to the modifier determines the extent of the rounding effect.

Rectangle()
    .cornerRadius(10.0)

Alternatively, SwiftUI also provides a standard RoundedRectangle view for creating a rounded rectangle:

RoundedRectangle(cornerRadius: 25.0)

Unfortunately, both the cornerRadius modifier and the RoundedRectangle view can only apply the same corner radius to all corners of the shape.

What if you need to round a specific corner of a view?

In iOS 17, the SwiftUI framework introduces a new view called UnevenRoundedRectangle. What sets this view apart is the ability to specify a distinct radius value for each corner, allowing developers to create highly customizable shapes.

Working with UnevenRoundedRectangle

With UnevenRoundedRectangle, you can easily create rectangular shapes with rounded corners of different radii. To use UnevenRoundedRectangle, you simply need to specify the corner radius for each corner. Here is an example:

UnevenRoundedRectangle(cornerRadii: .init(
                                                    topLeading: 50.0, 
                                                    bottomLeading: 10.0, 
                                                    bottomTrailing: 50.0, 
                                                    topTrailing: 30.0), 
                                                    style: .continuous)
    .frame(width: 300, height: 100)
    .foregroundStyle(.indigo)

Optionally, you can indicate the style of the corners. A continuous corner style will give the corners a smoother look. If you’ve put the code above in Xcode 15, you can create a rectangular shape like below.

Figure 1. A sample uneven rounded rectangle
Figure 1. A sample uneven rounded rectangle

You can use this shape and transform it into a button by using the background modifier. Here is a sample code snippet:

To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.

results matching ""

    No results matching ""