[英]How to create rounded UIButton with top-left & bottom-left corner radius only
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: 我尝试创建以下扩展,取自stackoverflow之一:
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
}
}
then called the method like this: 然后调用这样的方法:
self.collectionBtn.roundCorners(.TopLeft | .BottomLeft, radius: cornerRadius)
this code generates the following shape 此代码生成以下形状
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. 安装带圆角的路径时,它基本上会“刮掉”2个角。 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. 但是,您需要将填充颜色设置为清除。
Change your code like this: 像这样更改你的代码:
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);
}
}
Your syntax for setting the corners won't work in Swift 2: 设置角落的语法在Swift 2中不起作用:
self.collectionBtn.roundCorners(.TopLeft | .BottomLeft, radius: 10)
Should be 应该
self.collectionBtn.roundCorners([.TopLeft, .BottomLeft], radius: 10)
Here is how you can do it: 以下是如何做到这一点:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.