Round Top Corners of a UIButton in Swift

前端 未结 10 1943
情深已故
情深已故 2020-11-27 16:33

I know I can round all four corners using:

 myBtn.layer.cornerRadius = 8
 myBtn.layer.masksToBounds = true

Since I only want to round two,

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 17:16

    That's what helped me

    extension UIView {
    
       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
       }
    }
    

    Pay attention to the fact that if you have layout constraints attached to it, you must refresh this as follows in your UIView subclass:

    override func viewDidLayoutSubviews() {
       super.viewDidLayoutSubviews()
    
       yourButtonOutletName.roundCorners(
          corners: [.topLeft, .topRight],
          radius: yourButtonOutletName.frame.height / 2
       )
    }
    

提交回复
热议问题