如何创建仅具有左上角和左下角半径的圆形 UIButton

How to create rounded UIButton with top-left & bottom-left corner radius only

我需要创建一个像这样的左上角和左下角半径的按钮 。我尝试创建以下从 Whosebug 答案中获取的扩展:

extension UIButton {

   func roundCorners(corners:UIRectCorner, radius: CGFloat) {
       self.layer.borderColor = GenerateShape.UIColorFromHex(0x989898, alpha: (1.0-0.3)).CGColor
       self.layer.borderWidth = 1.0
       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

   }
}

然后像这样调用方法:

self.collectionBtn.roundCorners(.TopLeft | .BottomLeft, radius: cornerRadius) 

此代码生成以下形状

那么为什么左上角和左下角不可见呢?我应该怎么做才能让它们可见?

您的代码正在为您的按钮应用遮罩层。这会导致您在遮罩层中安装的形状之外的任何东西都被遮盖掉。当您安装带圆角的路径时,它实际上 "shaves off" 2 个角。这不是你想要的。

您可能想要创建一个形状层并将其安装为按钮层的常规子层,而不是蒙版层。但是,您需要将填充颜色设置为透明。

像这样更改您的代码:

extension UIButton 
{
  func roundCorners(corners:UIRectCorner, radius: CGFloat) 
  {
    let borderLayer = CAShapeLayer()
    borderLayer.frame = self.layer.bounds
    borderLayer.strokeColor = GenerateShape.UIColorFromHex(0x989898, 
      alpha: (1.0-0.3)).CGColor
    borderLayer.fillColor = UIColor.clearColor().CGColor
    borderLayer.lineWidth = 1.0
    let path = UIBezierPath(roundedRect: self.bounds, 
      byRoundingCorners: corners, 
      cornerRadii: CGSize(width: radius, height: radius))
    borderLayer.path = path.CGPath
    self.layer.addSublayer(borderLayer);
  }
}

编辑:

您设置角点的语法在 Swift 2:

中不起作用
self.collectionBtn.roundCorners(.TopLeft | .BottomLeft, radius: 10)

应该是

self.collectionBtn.roundCorners([.TopLeft, .BottomLeft], radius: 10)

以下是您的操作方法:

CGRect maskRect = CGRectMake(0.0, 0.0, CGRectGetWidth(<#something here#>), CGRectGetHeight(<#something here#>));
CAShapeLayer *maskLayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:maskRect
                                           byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerTopLeft)
                                                 cornerRadii:CGSizeMake(<#corner radius#>, <#corner radius#>)];
maskLayer.path = path.CGPath;
self.layer.mask = maskLayer;