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

2

7

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.

Nonintervention answered 10/9, 2014 at 15:26 Comment(2)
Why are you setting the background color with an image instead of with a UIColor? If your image is 1px x 1px, it's already a solid color. Alternatively, you could use the UIColor method colorWithPatternImage:Hailstone
I need to set the highlighted state background color, UIKit provides no means of doing this, hence the category. However, doing it this way kills the rounded corners, that’s what I need to fix.Nonintervention
N
17

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

Nonintervention answered 12/9, 2014 at 10:24 Comment(0)
H
2

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];
}
Hailstone answered 10/9, 2014 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.