hivesolutions / cameo

A generic framework for iOS interaction
http://cameo.hive.pt
Apache License 2.0
0 stars 0 forks source link

Support for setting background color for a state in UIButton #7

Closed tsilva closed 9 years ago

tsilva commented 9 years ago

Description

Buttons only support [button setBackgroundImage:forState:]. The following category method can be added to UIButton to solve this:

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    UIImage *image = [UIImage imageWithColor:backgroundColor];
    [self setBackgroundImage:image forState:state];
}

And the following to UIImage:

+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0, 0.0, 1.0, 1.0);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}