Change the color of the UIButton BG on the selected, but keep the radius of the corner of the layer?

Im changes the background color UIButtonusing this category method using a 1px image by 1px:

- (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 .layer.cornerRadius. I need a button with rounded corners, but also one whose background color I can change to the selected one.

How to get around this? The radius of the angle must be dynamic.

+4
source share
2 answers

So, all I had to do was make sure it was button.layer.masksToBoundson. The problem is resolved; no subclass is required.

+8
source

UIButton. init. xib, initWithDecoder:

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

    return self;
}

setHighlighted:. . "" . , . .

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

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

All Articles