带有圆角和边框的UIButton

And*_*ych 2 iphone cocoa-touch rounded-corners uibutton ios

我只想在一侧设置UIButton的边框和圆角

我使用以下代码:

//set rounded corners on top
UIBezierPath *maskPath =  [UIBezierPath bezierPathWithRoundedRect:self.scanButton.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(10.0, 10.0)];

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.scanButton.bounds;
maskLayer.path = maskPath.CGPath;

self.scanButton.layer.mask = maskLayer;

// set border
self.scanButton.layer.borderColor = [UIColor blackColor].CGColor;
self.scanButton.layer.borderWidth = 2.0f;
[self.scanButton.layer setMasksToBounds:YES];
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如何在上角设置适当的边框?

ale*_*pls 5

Swift 2.0版本

边框的边角正在修剪,因为您可能已经在UIView本身上设置了视图的背景色。更好的方法是直接在图层上设置填充颜色。可以这样完成:

let button = ... // your existing UIButton
let borderLayer = CAShapeLayer()
borderLayer.strokeColor = UIColor.blackColor().CGColor
borderLayer.fillColor = UIColor.yellowColor().CGColor
borderLayer.borderWidth = 2.0

let borderPath = UIBezierPath(roundedRect: button.bounds,
    byRoundingCorners: [.TopLeft, .TopRight],
    cornerRadii: CGSize(width:10.0, height: 10.0))
    borderLayer.path = borderPath.CGPath

button.layer.insertSublayer(borderLayer, atIndex: 0)
Run Code Online (Sandbox Code Playgroud)

上面将为您提供此结果而不会出现弯角:

示例按钮

我使用这种方法将UIButton子类放在一起,可以在按钮的每个角上分别设置边框半径,请在此处进行检查:https : //gist.github.com/alexpls/95279b3f9a2da7f2d7bf,希望对您有所帮助!