Rounded UIView using CALayers - only some corners - How?

后端 未结 14 2302
南方客
南方客 2020-11-22 13:53

In my application - there are four buttons named as follows:

  • Top - left
  • Bottom - left
  • Top - right
  • Bottom - right

Abov

14条回答
  •  时光说笑
    2020-11-22 14:11

    Half a decade late, but I think the current way people do this isn't 100% right. Many people have had the issue that using the UIBezierPath + CAShapeLayer method interferes with Auto-layout, especially when it is set on the Storyboard. No answers go over this, so I decided to add my own.

    There is a very easy way to circumvent that: Draw the rounded corners in the drawRect(rect: CGRect) function.

    For example, if I wanted top rounded corners for a UIView, I'd subclass UIView and then use that subclass wherever appropriate.

    import UIKit
    
    class TopRoundedView: UIView {
    
        override func drawRect(rect: CGRect) {
            super.drawRect(rect)
    
            var maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: UIRectCorner.TopLeft | UIRectCorner.TopRight, cornerRadii: CGSizeMake(5.0, 5.0))
    
            var maskLayer = CAShapeLayer()
            maskLayer.frame = self.bounds
            maskLayer.path = maskPath.CGPath
    
            self.layer.mask = maskLayer
        }
    }
    

    This is the best way to conquer the issue and doesn't take any time at all to adapt to.

提交回复
热议问题