Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone : How to set BackgroundColor of UIButton with buttonType UIButtonTypeCustom

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

[button setBackgroundColor:[UIColor redColor]]; 

but this shows red color only on the four corners of button not on the whole button and also when i use forState:UIControlStateNormal then the application hangs. Is their any way to show some color on button when clicked?

[click1 setBackgroundColor:[UIColor redColor] forState:UIControlStateHighlighted]; 

Any help will be appreciated.

like image 597
Pankaj Kainthla Avatar asked Oct 29 '10 05:10

Pankaj Kainthla


1 Answers

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.

like image 108
Hendrik Avatar answered Sep 28 '22 23:09

Hendrik