Skip to content

How to round corners specifically on a UIView

1 min read

KOR

To round a corner on a UIView, you can set the layer’s cornerRadius value. Simply use it like this:

cornerView.layer.cornerRadius = 8

To ensures subviews are clipped to the rounded corners, add ‘view.clipsToBounds = true’.

But what if you need to corner only to top view or bottom? We need to set the CALayer’s maskedCorners property. You can make an extension for making a rounded corner like this:

extension UIView {
    // Available from iOS 11.0
    func cornerRadius(_ corners: UIRectCorner..., radius: CGFloat) {
        layer.cornerRadius = radius
        
        var maskedCorners: CACornerMask = []
        let cornerSet = corners.isEmpty ? [.allCorners] : corners
        
        if cornerSet.contains(.allCorners) {
            maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        } else {
            if cornerSet.contains(.topLeft) {
                maskedCorners.insert(.layerMinXMinYCorner)
            }
            if cornerSet.contains(.topRight) {
                maskedCorners.insert(.layerMaxXMinYCorner)
            }
            if cornerSet.contains(.bottomLeft) {
                maskedCorners.insert(.layerMinXMaxYCorner)
            }
            if cornerSet.contains(.bottomRight) {
                maskedCorners.insert(.layerMaxXMaxYCorner)
            }
        }
        
        layer.maskedCorners = maskedCorners
    }
}

This extension provides the following features

The below table show mapping between CACornerMask and corner.

CACornerMaskCorner
layerMinXMinYCornertop left corner
layerMaxXMinYCornertop right corner
layerMinXMaxYCornerbottom left corner
layerMaxXMaxYCornerbottom right corner

// Usage

// All corners rounded
circleView.cornerRadius(.allCorners, radius: 50)

// Only top corners rounded
circleView.cornerRadius(.topLeft, .topRight, radius: 50)

// Only left corners rounded
circleView.cornerRadius(.topLeft, .bottomLeft, radius: 25)

// Only diagonal corners rounded
circleView.cornerRadius(.topLeft, .bottomRight, radius: 25)

Related Resources

cornerRadius

maskedCorners


Share this post on:

Previous Post
주니어 개발자의 마지막, 미드레벨(mid-level) 개발자의 시작
Next Post
How to create a view controller from xib