Posts How to round corners specifically on a UIView
Post
Cancel

How to round corners specifically on a UIView

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

1
2
cornerView.layer.cornerRadius = 8
cornerView.layer.clipsToBound = true    // to make the corner work, clipsToBound must be true

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

1
2
3
4
5
6
7
8
9
10
11
12
extension UIView {
    // available from iOS 11.0
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        self.layer.cornerRadius = radius
        var cornerMask = CACornerMask()
        if corners.contains(.topLeft) { cornerMask.insert(.layerMinXMinYCorner) }
        if corners.contains(.topRight) { cornerMask.insert(.layerMaxXMinYCorner) }
        if corners.contains(.bottomLeft) { cornerMask.insert(.layerMinXMaxYCorner) }
        if corners.contains(.bottomRight) { cornerMask.insert(.layerMaxXMaxYCorner) }
        self.layer.maskedCorners = cornerMask
    }
}
This post is licensed under CC BY 4.0 by the author.

How to create a view controller from xib

주니어 개발자의 마지막, 미드레벨(mid-level) 개발자의 시작