Sumi-Interactive / SIAlertView

An UIAlertView replacement with block syntax and fancy transition styles.
MIT License
2.51k stars 424 forks source link

Setting Colors for Buttons Instead of Images? #72

Open vicc opened 10 years ago

vicc commented 10 years ago

Is there a way to define the button using uicolors rather than enum's for images?

juzooda commented 9 years ago

That would be cool

ghost commented 9 years ago

Just came across this project and wanting the same thing. As your posts are old, don't know if you still need the help, but in any case, heres what I did.

Added:

- (UIImage *)imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Then for the buttons in buttonForItemIndex:

    switch (item.type) {
        case SIAlertViewButtonTypeCancel:
            normalImage = [self imageFromColor:[UIColor colorWithRed:0.271 green:0.271 blue:0.271 alpha:0.75]];
            highlightedImage = [self imageFromColor:[UIColor colorWithRed:0.271 green:0.271 blue:0.271 alpha:1]];

            [button setTitleColor:self.cancelButtonColor forState:UIControlStateNormal];
            [button setTitleColor:[self.cancelButtonColor colorWithAlphaComponent:0.8] forState:UIControlStateHighlighted];
            break;

        case SIAlertViewButtonTypeDestructive:
            normalImage = [self imageFromColor:[UIColor colorWithRed:0.678 green:0.161 blue:0.188 alpha:0.50]];
            highlightedImage = [self imageFromColor:[UIColor colorWithRed:0.678 green:0.161 blue:0.188 alpha:0.65]];

            [button setTitleColor:self.destructiveButtonColor forState:UIControlStateNormal];
            [button setTitleColor:[self.destructiveButtonColor colorWithAlphaComponent:0.8] forState:UIControlStateHighlighted];
            break;

        case SIAlertViewButtonTypeDefault:
        default:
            normalImage = [self imageFromColor:[UIColor colorWithRed:0.271 green:0.271 blue:0.271 alpha:0.75]];
            highlightedImage = [self imageFromColor:[UIColor colorWithRed:0.271 green:0.271 blue:0.271 alpha:1]];

            [button setTitleColor:self.buttonColor forState:UIControlStateNormal];
            [button setTitleColor:[self.buttonColor colorWithAlphaComponent:0.8] forState:UIControlStateHighlighted];
            break;
    }

Obviously defining corner radius would look ideal too: button.layer.cornerRadius = 8; button.clipsToBounds = YES;

Customizing font, title, word wrap etc to fit your styling needs, but that's the jist of what I did.

Hope this helps.