我知道我可以使用以下方法绕过所有四个角:
myBtn.layer.cornerRadius = 8 myBtn.layer.masksToBounds = true
因为我只是想第二轮中,我做了一些研究,发现这个:
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 , .TopRight], radius: 10)
但是,这不适用于UIButton。当我将扩展名切换为UIButton类型并将其传递给button时,输出如下所示:
问题是,如何使它适应于UIButton?
添加UIButton扩展:
extension UIButton{ func roundedButton(){ let maskPath1 = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 8, height: 8)) let maskLayer1 = CAShapeLayer() maskLayer1.frame = bounds maskLayer1.path = maskPath1.cgPath layer.mask = maskLayer1 } }
在viewDidAppear / viewDidLayoutSubviews中调用:
btnCorner.roundedButton()
按钮角输出: