NEW: Get your ticket to Hacking with Swift Live 2020! >>

How to clip a view so only part is visible

Paul Hudson    @twostraws   

Fully updated for Xcode 11.3

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 Why the top iOS apps rely on Instabug for crash reporting. Crash reporting + Bug reporting + Customizable in-app surveys all in one SDK. Know which line of code caused the crash along with network logs, repro steps, and the session profiler to identify and resolve severe crashes quickly. See more detailed features comparison and try Instabug for free here.

Support my work on Patreon

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.4/5