iPhone : How to set BackgroundColor of UIButton with buttonType UIButtonTypeCustom

You could create an image programmatically and so have the ability to use your colors in a dynamic way:

Create a category for UIButton with this method and be sure to have QuartzCore lib imported via @import QuartzCore:

- (void)setColor:(UIColor *)color forState:(UIControlState)state
{
    UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    colorView.backgroundColor = color;

    UIGraphicsBeginImageContext(colorView.bounds.size);
    [colorView.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *colorImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setBackgroundImage:colorImage forState:state];
}

This is gonna create an image with the size of your button for your specified color and then assigning it for the wished state. Because of the usage of the backgroundImage you can still set a title for the button via the setTitle:forState: method.

Leave a Comment