Change UIButton BG color on highlighted, but preserve layer corner radius?

2.4k Views Asked by At

I’m changing the background colour of a UIButton via this category method, using a 1px by 1px image:

- (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();
}

However, this overrides my setting of the .layer.cornerRadius. I need a button with rounded corners, but also one whose background colour I can change on highlighted.

Any way around this? The corner radius needs to be dynamic.

2

There are 2 best solutions below

0
Luke On BEST ANSWER

So, all I had to do was ensure that button.layer.masksToBounds was turned on. Problem solved, no subclassing required.

0
Sean Kladek On

Subclass the UIButton. In your subclass, set the corner radius in the init method. If you're using a xib, this will be initWithDecoder:

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

    return self;
}

Also subclass the setHighlighted: method. This is where you'll set the background color. Check the "highlighted" value and assign the background color appropriately. In this example, the button is a blue button that is red on highlight with rounded corners. You will need to set the initial color in the nib.

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

    self.backgroundColor = (highlighted) ? [UIColor redColor] : [UIColor blueColor];
}