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

后端 未结 26 2997
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  悲&欢浪女
    2020-11-22 07:05

    Here is a Swift version of @JohnnyRockex answer

    extension UIView {
    
        func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
             let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
             let mask = CAShapeLayer()
             mask.path = path.cgPath
             self.layer.mask = mask
        }
    
    }
    

    view.roundCorners([.topLeft, .bottomRight], radius: 10)
    

    Note

    If you're using Auto Layout, you'll need to subclass your UIView and call roundCorners in the view's layoutSubviews for optimal effect.

    class View: UIView {
        override func layoutSubviews() {
            super.layoutSubviews()
    
            self.roundCorners([.topLeft, .bottomLeft], radius: 10)
        }
    }
    

提交回复
热议问题