문제

I have a subclassed 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];
    }
}

The default state of the button has a 1.0 bottom border. When it is selected, the border should become 3.0. How can I clear the previously added layer and re add a 1.0 border when a user toggles a button?

도움이 되었습니까?

해결책

I believe there is an easier way to do what you need. If you subclass the UIButton just because you just want to have different types button border, you can try a different way but a lot easier.

Use 2 different button background image, one with border 1 and another with border 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];

With an additional button image, it might just take extra 10 kb on your project.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top