Search code examples
iosobjective-cuibuttoncglayer

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


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.


Solution

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