Rounded UIView using CALayers - only some corners - How?

后端 未结 14 2284
南方客
南方客 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:21

    To add to to the answer and the addition, I created a simple, reusable UIView in Swift. Depending on your use case, you might want to make modifications (avoid creating objects on every layout etc.), but I wanted to keep it as simple as possible. The extension allows you to apply this to other view's (ex. UIImageView) easier if you do not like subclassing.

    extension UIView {
    
        func roundCorners(_ roundedCorners: UIRectCorner, toRadius radius: CGFloat) {
            roundCorners(roundedCorners, toRadii: CGSize(width: radius, height: radius))
        }
    
        func roundCorners(_ roundedCorners: UIRectCorner, toRadii cornerRadii: CGSize) {
            let maskBezierPath = UIBezierPath(
                roundedRect: bounds,
                byRoundingCorners: roundedCorners,
                cornerRadii: cornerRadii)
            let maskShapeLayer = CAShapeLayer()
            maskShapeLayer.frame = bounds
            maskShapeLayer.path = maskBezierPath.cgPath
            layer.mask = maskShapeLayer
        }
    }
    
    class RoundedCornerView: UIView {
    
        var roundedCorners: UIRectCorner = UIRectCorner.allCorners
        var roundedCornerRadii: CGSize = CGSize(width: 10.0, height: 10.0)
    
        override func layoutSubviews() {
            super.layoutSubviews()
            roundCorners(roundedCorners, toRadii: roundedCornerRadii)
        }
    }
    

    Here's how you would apply it to a UIViewController:

    class MyViewController: UIViewController {
    
        private var _view: RoundedCornerView {
            return view as! RoundedCornerView
        }
    
        override func loadView() {
            view = RoundedCornerView()
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            _view.roundedCorners = [.topLeft, .topRight]
            _view.roundedCornerRadii = CGSize(width: 10.0, height: 10.0)
        }
    }
    

提交回复
热议问题