如何使用左上角&创建圆形的UIButton;仅左下角半径 [英] How to create rounded UIButton with top-left & bottom-left corner radius only
问题描述
我需要创建一个带有左上角&的按钮像这样的左下角半径.我尝试通过创建以下扩展名来尝试,该扩展名来自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屋!