6

我正在UIButton通过这种类别方法更改 a 的背景颜色,使用 1px x 1px 图像:

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state
{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), NO, 0);
    [backgroundColor setFill];
    CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, 1, 1));
    UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
    [self setBackgroundImage:backgroundImage forState:state];
    UIGraphicsEndImageContext();
}

但是,这会覆盖我的.layer.cornerRadius. 我需要一个带圆角的按钮,但也需要一个可以在突出显示时更改其背景颜色的按钮。

有什么办法吗?拐角半径需要是动态的。

4

2 回答 2

15

所以,我所要做的就是确保它button.layer.masksToBounds已打开。问题解决了,不需要子类化。

于 2014-09-12T10:24:05.910 回答
2

子类化 UIButton。在您的子类中,在 init 方法中设置角半径。如果您使用的是 xib,这将是 initWithDecoder:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.layer.cornerRadius = 5.f;
    }

    return self;
}

也是 setHighlighted: 方法的子类。这是您设置背景颜色的地方。检查“突出显示”值并适当地分配背景颜色。在此示例中,该按钮是一个蓝色按钮,在高亮时显示为红色并带有圆角。您需要在笔尖中设置初始颜色。

- (void)setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];

    self.backgroundColor = (highlighted) ? [UIColor redColor] : [UIColor blueColor];
}
于 2014-09-10T16:06:51.143 回答