iPhone : How to set BackgroundColor of UIButton with buttonType UIButtonTypeCustom

前端 未结 15 1459
有刺的猬
有刺的猬 2020-12-01 13:45

i want to change the button color when it is clicked. I used :

[button setBackgroundColor:[UIColor redColor]];

but this shows red color onl

15条回答
  •  鱼传尺愫
    2020-12-01 14:31

    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.

提交回复
热议问题