UIView round specific corners only Swift

If you looking to make round only specific corners of the UIView then you are at the right place.
Create a new swift file and add below UIView Extension in the file.
import UIKit

extension UIView {
    
    func round(corners: UIRectCorner, cornerRadius: Double) {
        
        let size = CGSize(width: cornerRadius, height: cornerRadius)
        let bezierPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: size)
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = self.bounds
        shapeLayer.path = bezierPath.cgPath
        self.layer.mask = shapeLayer
    }
}

In the above code we create a UIBezierPath using provided corners and assign it to CAShapeLayer.

Round only top corners

Write below code to round only top corners
self.myView.round(corners: [.topLeft, .topRight], cornerRadius: 20)

Round only bottom corners

self.myView.round(corners: [.bottomLeft, .bottomRight], cornerRadius: 20)

Round other corners

// Round top-left corner only
self.myView.round(corners: [.topLeft], cornerRadius: 20)
        
// Round top-left and bottom-left corners only
self.myView.round(corners: [.topLeft, .bottomLeft], cornerRadius: 20)
        
// Round top-left and bottom-right corners only
self.myView.round(corners: [.topLeft, .bottomRight], cornerRadius: 20)
        
// Round top-right and bottom-left corners only
self.myView.round(corners: [.topRight, .bottomLeft], cornerRadius: 20)

Read our next Article: Sending data from iPhone to Apple Watch and vice versa using Swift 5

1 comment on “UIView round specific corners only Swift

  1. Coy Kaub

    Terrifying. Just the thought of having unlimited booze sends a shiver down my liver. It’s truly a good thing that I’m limited by my own poverty. But thanks though, hey.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *