在带有圆角的UIButton中添加底部边框

时间:2014-05-23 10:04:05

标签: ios objective-c uibutton

如何在带圆角的UIButton中添加右边框和左边框?

这是我的按钮,我也希望边框有圆角:

我按钮的源代码:

- (void)initialise;
    {
        //add border
        [self addBottomBorderWithColor:[UIColor grayColor] andWidth:2];
        [self addRightBorderWithColor:[UIColor grayColor] andWidth:2];

        //round
        self.layer.cornerRadius  = 8.0f;
    }

    - (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth
    {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;

        border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
        [self.layer addSublayer:border];
    }

    - (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth
    {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;

        border.frame = CGRectMake(self.frame.size.width, 0, borderWidth, self.frame.size.height);
        [self.layer addSublayer:border];
    }

1 个答案:

答案 0 :(得分:3)

您可以添加一个略大于按钮的CALayer,并使用负边距对其进行偏移,以便隐藏顶部和左侧边框。请注意,我现在无法测试它,它可能需要进一步调整,但它应该给你一般的想法:

-(void)initialise;
{
    //add border
    [self addBorderWithColor:[UIColor grayColor] andWidth:2];
    //round
    self.layer.cornerRadius  = 8.0f;
}

- (void)addBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth
{
    CALayer *border = [CALayer layer];
    border.borderColor = color.CGColor;
    border.frame = CGRectMake(-borderWidth, -borderWidth, self.frame.size.width+borderWidth, self.frame.size.height+borderWidth);
    border.borderWidth = borderWidth;
    border.cornerRadius = 8.f;
    [self.layer addSublayer:border];
    self.layer.masksToBounds = YES;
}