Updated for Xcode 14.0 beta 1
SwiftUI lets you clip any view to control its shape, all by using the clipShape()
modifier.
For example this creates a button using the system image “bolt.fill” (a filled lightning bolt), gives it some padding and a background color, then clips it using a circle so that we get a circular button:
Button {
print("Button was pressed!")
} label: {
Image(systemName: "bolt.fill")
.foregroundColor(.white)
.padding()
.background(.green)
.clipShape(Circle())
}
Download this as an Xcode project
The Circle
clip shape will always make circles from views, even if their width and height are unequal – it will just crop the larger value to match the small.
As well as Circle
there’s also Capsule
, which crops a view to have rounded corners in a lozenge shape. For example, this creates the same button using a capsule shape:
Button {
print("Pressed!")
} label: {
Image(systemName: "bolt.fill")
.foregroundColor(.white)
.padding(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 20))
.background(.green)
.clipShape(Capsule())
}
Download this as an Xcode project
I added some more precise padding there to get a better shape – you should experiment to find something you like.
SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.