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.
So, all I had to do was ensure that button.layer.masksToBounds
was turned on. Problem solved, no subclassing required.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With