Updated for Xcode 14.2
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())
}
}
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.
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.