Last Updated: February 25, 2016
·
1.832K
· tnys

UIButton and setBackgroundColor:forState:

Ever wanted to have a 'setBackgroundColor:forState:' method in UIButton, just like the already existing 'setBackgroundImage:forState:' method? Look no further, and grab the category below!

@implementation UIButton (setBackgroundColorForState)

- (void) setBackgroundColor:(UIColor *) _backgroundColor forState:(UIControlState) _state {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(3, 3), NO, [UIScreen mainScreen].scale);
    UIBezierPath* p = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 3, 3)];
    [_backgroundColor setFill];
    [p fill];
    UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
    [self setBackgroundImage:[img resizableImageWithCapInsets:UIEdgeInsetsMake(1, 1, 1, 1)] forState:_state];
}