How to round only specific corners to a UIView in iOS using Swift

How to round only specific corners to a UIView in iOS using Swift

Sometimes you only want to round one or two corners from your UIView.
Use the following code to round specific corners:

if #available(iOS 11.0, *){
myUIView.clipsToBounds = true
myUIView.layer.cornerRadius = 5
myUIView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}else{
let path = UIBezierPath(roundedRect: myUIView.bounds,byRoundingCorners:[.topLeft, .topRight],cornerRadii: CGSize(width: 5, height: 5))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
myUIView.layer.mask = maskLayer
}

 

As you see, for devices with iOS 10 and below, we use UIBezierPath to draw the path on our UIView.

For iOS 11 and above, we use maskedCorners in array.
Here’s the list of the corners:

.layerMinXMinYCorner = Top Left Corner
.layerMaxXMinYCorner = Top Right Corner
.layerMinXMaxYCorner = Bottom Left Corner
.layerMaxXMaxYCorder = Bottom Right Corner

If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!

Leave a Reply

avatar
  Subscribe  
Notify of

Stay Connected

Newsletter

Subcribe for weekly emails! Get my posts of the week right in your inbox!