Round Top Corners of a UIButton in Swift

前端 未结 10 1951
情深已故
情深已故 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:09

    For swift 5 and the most flexibility

    Define an extension with a roundCorners function

    extension UIButton {
        func roundCorners(corners: UIRectCorner, radius: Int = 8) {
            let maskPath1 = UIBezierPath(roundedRect: bounds,
                                         byRoundingCorners: corners,
                                         cornerRadii: CGSize(width: radius, height: radius))
            let maskLayer1 = CAShapeLayer()
            maskLayer1.frame = bounds
            maskLayer1.path = maskPath1.cgPath
            layer.mask = maskLayer1
        }
    }
    

    Call the roundCorners function

    myButton.roundCorners(corners: [.topLeft, .topRight])
    

    Or with a specific radius

    myButton.roundCorners(corners: [.topLeft, .topRight], radius: 20)
    

提交回复
热议问题