选中时更改厚度的UIButton边框

时间:2014-05-15 09:20:43

标签: ios objective-c ios7 uibutton

我有一个子类UIButton

- (void)configureButton
{
    self.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    CALayer *border = [CALayer layer];
    border.backgroundColor = [UIColor whiteColor].CGColor;
    border.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width, 1.0);
    [self.layer addSublayer:border];
}

- (void)setSelected:(BOOL)selected
{
    [super setSelected:selected];
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];

    // remove all layers ?
    if (selected) {

        CALayer *border = [CALayer layer];
        border.backgroundColor = [UIColor whiteColor].CGColor;

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

        self.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    } else {

        CALayer *border = [CALayer layer];
        border.backgroundColor = [UIColor whiteColor].CGColor;

        border.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width,1.0);
        [self.layer addSublayer:border];
        self.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    }
}

按钮的默认状态具有1.0底部边框。选中后,边框应为3.0。当用户切换按钮时,如何清除以前添加的图层并重新添加1.0边框?

1 个答案:

答案 0 :(得分:1)

我相信有一种更简单的方法可以满足您的需求。如果你只是因为你只想拥有不同类型的按钮边框来继承UIButton,你可以尝试不同的方式但更容易。

使用2个不同的按钮背景图像,一个带边框1,另一个带边框3。

[self.button setBackgroundImage:[UIImage imageNamed:@"ImageWithBorder1"] forState:UIControlStateNormal];
[self.button setBackgroundImage:[UIImage imageNamed:@"ImageWithBorder3"] forState:UIControlStateHighlighted];
[self.button setBackgroundImage:[UIImage imageNamed:@"ImageWithBorder3"] forState:UIControlStateSelected];

使用额外的按钮图像,可能只需要额外10 kb的项目。