NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to clip a view so only part is visible

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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

A white lightning bolt icon inside a green 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 {
    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

A white lightning bolt icon inside a green capsule or pill shape.

I added some more precise padding there to get a better shape – you should experiment to find something you like.

Hacking with Swift is sponsored by Waldo

SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.

Try for free today!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.3/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.