Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 352
Luke Avatar asked Sep 10 '14 15:09

Luke


Video Answer


2 Answers

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

like image 115
Luke Avatar answered Oct 21 '22 04:10

Luke


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];
}
like image 35
Sean Kladek Avatar answered Oct 21 '22 04:10

Sean Kladek