Skip to main content

When should you use ContainerRelativeShape?

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

When should you use ContainerRelativeShape? 관련

SwiftUI by Example

Back to Home

When should you use ContainerRelativeShape? | SwiftUI by Example

When should you use ContainerRelativeShape?

Updated for Xcode 15

SwiftUI has a number of built-in shapes that are self-explanatory, but there's one that stands out: ContainerRelativeShape. This isn't a fixed shape, but is instead designed to be an insettable version of whatever shape it's placed inside, which is particularly important when creating home screen widgets.

Important

At this time, ContainerRelativeShape works only inside widgets. You can use it elsewhere, but it will just make a rectangle.

For example, we could write code that draws a blue shape in our widget, and use ContainerRelativeShape to make sure it's the same shape as the widget itself:

struct ContentView: View {    
    var body: some View {
        ZStack {
            ContainerRelativeShape()
                .inset(by: 4)
                .fill(.blue)

            Text("Hello, World!")
                .font(.title)
        }
        .frame(width: 300, height: 200)
        .background(.red)
        .clipShape(Capsule())
    }
}
An iOS widget showing the word Hello against a blue background, with a red border.
An iOS widget showing the word Hello against a blue background, with a red border.

SwiftUI is smart here: as you inset the container shape further and further, it will scale the corner radius of the container so it looks great in your widget.

Similar solutions…
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
Answering the big question: should you learn SwiftUI, UIKit, or both? | SwiftUI by Example

Answering the big question: should you learn SwiftUI, UIKit, or both?
How to use Instruments to profile your SwiftUI code and identify slow layouts | SwiftUI by Example

How to use Instruments to profile your SwiftUI code and identify slow layouts
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
What's the difference between @ObservedObject, @State, and @EnvironmentObject? | SwiftUI by Example

What's the difference between @ObservedObject, @State, and @EnvironmentObject?

이찬희 (MarkiiimarK)
Never Stop Learning.