How to set cornerRadius for only top-left and top-right corner of a UIView?

后端 未结 26 3322
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 06:14

Is there a way to set cornerRadius for only top-left and top-right corner of a UIView?

I tried the following, but it end up not seeing the

26条回答
  •  Happy的楠姐
    2020-11-22 07:13

    Another version of Stephane's answer.

    import UIKit
    
        class RoundCornerView: UIView {
        var corners : UIRectCorner = [.topLeft,.topRight,.bottomLeft,.bottomRight]
            var roundCornerRadius : CGFloat = 0.0
            override func layoutSubviews() {
                super.layoutSubviews()
                if corners.rawValue > 0 && roundCornerRadius > 0.0 {
                    self.roundCorners(corners: corners, radius: roundCornerRadius)
                }
            }
            private func roundCorners(corners: UIRectCorner, radius: CGFloat) {
                let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
                let mask = CAShapeLayer()
                mask.path = path.cgPath
                layer.mask = mask
            }
    
        }
    

提交回复
热议问题