How can I set a custom background color of a button?
Interface Builder doesn\'t seem to have an interface to do this.
Is it only available programmatically
It seems, that button color still is an issue. The following category sets a button's backgroundimage completely programmatically via an instance method that takes a UIColor parameter. There is no need to create button backgroundimage files. It preserves button behavior based on UIControlState. And it keeps the rounded corners.
The header file UIButton+ColoredBackground.h
#import
@interface UIButton (ColoredBackground)
- (void)setBackgroundImageByColor:(UIColor *)backgroundColor forState:(UIControlState)state;
@end
and the content of UIButton+ColoredBackground.m
#import "UIButton+ColoredBackground.h"
#import
@implementation UIButton (ColoredBackground)
- (void)setBackgroundImageByColor:(UIColor *)backgroundColor forState:(UIControlState)state{
// tcv - temporary colored view
UIView *tcv = [[UIView alloc] initWithFrame:self.frame];
[tcv setBackgroundColor:backgroundColor];
// set up a graphics context of button's size
CGSize gcSize = tcv.frame.size;
UIGraphicsBeginImageContext(gcSize);
// add tcv's layer to context
[tcv.layer renderInContext:UIGraphicsGetCurrentContext()];
// create background image now
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// set image as button's background image for the given state
[self setBackgroundImage:image forState:state];
UIGraphicsEndImageContext();
// ensure rounded button
self.clipsToBounds = YES;
self.layer.cornerRadius = 8.0;
[tcv release];
}
@end
The new method is justed called on every UIButton instance like:
[myButton setBackgroundImageByColor:[UIColor greenColor] forState:UIControlStateNormal];