如何使用左上角创建圆形 UIButton &仅左下角半径 [英] How to create rounded UIButton with top-left & bottom-left corner radius only

查看:13
本文介绍了如何使用左上角创建圆形 UIButton &仅左下角半径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个左上角的按钮 &像这样的左下角半径 .我尝试创建以下扩展名,该扩展名取自 stackoverflow 答案之一:

I need to create a button with top-left & bottom-left corner radius like this one . I tried by creating the following extension that was taken from one of stackoverflow answer:

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) 

此代码生成以下形状

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

So why the top-left & bottom-left corner invisible? What should I do to make them visible?

推荐答案

您的代码正在将遮罩层应用到您的按钮.这会导致您在遮罩层中安装的形状之外的任何东西都被遮盖掉.当您安装带有圆角的路径时,它基本上会刮掉"两个角.这不是你想要的.

Your code is applying a mask layer to your button. that causes anything outside the shape you install in the mask layer to be masked away. When you install a path with rounded corners, it essentially "shaves off" the 2 corners. That's not what you want.

您可能希望创建一个形状图层并将其安装为按钮图层的常规子图层,而不是蒙版图层.但是,您需要将填充颜色设置为清除.

You probably want to create a shape layer and install it as a regular sublayer of your button's layer, not as the mask layer. You'll need to set the fill color to clear however.

像这样更改您的代码:

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 中不起作用:

Your syntax for setting the corners won't work in Swift 2:

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

应该是

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

这篇关于如何使用左上角创建圆形 UIButton &仅左下角半径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆