Categories
iOS Swift

Rounded Corners

Radius for all corners

I have used the possibility to make rounded corners on iOS. It’s quite straight forward using the CALayer of a view. Doing the following will round all 4 corners of the view.

extension UIView {
     
     func roundedCorners(_ radius: CGFloat) {
         layer.masksToBounds = true
         layer.cornerRadius = radius
     }
 } 

Adding radius for some corners

Is it possible to add a rounded corner to only 2 of the corners? The answer is yes, but with some limitations.

Apple provides an OptionSet to select which of the corners you want to add a radius. You can use them to add to your view like this

extension UIView {
     
     func roundedCorners(_ mask: CACornerMask, 
                         radius: CGFloat) {
         self.layer.cornerRadius = radius
         self.layer.maskedCorners = mask
     }
 } 
 
view.roundedCorners([.layerMinXMinYCorner,
                     .layerMinXMaxYCorner], 
                    radius: 30) 

CACornerMask is the Option set defining the 4 corners. Personally, I found the values not too intuitive, but here are their meaning.

case .layerMinXMinYCornertopLeft
case .layerMinXMaxYCornerbottomLeft
case .layerMaxXMaxYCornerbottomRight
case .layerMaxXMinYCornertopRight

What about the limitation?

You cannot set some corners with radius 10, and some other corners with radius 20. All of the corners will need to have the same values. If you need otherwise, you probably will need to compose 2 views together.

Thank you for reading until here…  👊 Have a good week end…  🍺