Updated for Xcode 12.0
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(action: {
print("Button tapped")
}) {
Image(systemName: "bolt.fill")
.foregroundColor(.white)
.padding()
.background(Color.green)
.clipShape(Circle())
}
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(action: {
print("Button tapped")
}) {
Image(systemName: "bolt.fill")
.foregroundColor(.white)
.padding(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 20))
.background(Color.green)
.clipShape(Capsule())
}
SPONSORED From January 26th to 31st you can join a FREE crash course for iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.