Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i set the background color of a particular button in iphone?

How can I set the background color of a particular button in iPhone?

I used:

btnName1 = [ColorfulButton buttonWithType:UIButtonTypeRoundedRect];
btnName1.frame=CGRectMake(45,146,220,40);
[btnName1 setTitle:@"Continue" forState:UIControlStateNormal]; 
[btnName1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
[btnName1 setImage:[UIImage imageNamed:@"green.png"] forState:UIControlStateNormal];
UIImage *img =[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"greenish" ofType:@"png"]];
UIImage *strechableImage = [img stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[btnName1 setBackgroundImage:strechableImage forState:UIControlStateNormal];
[btnName1 setNeedsDisplay];
[InfoView addSubview:btnName1];

It's correctly working on iPhone simulator but not on iPod (color not shown in iPod).

like image 667
iOS_User Avatar asked Nov 24 '25 14:11

iOS_User


2 Answers

myButton.backgroundColor = [UIColor redColor];

Or whatever colour you want. This method is inherited from UIView.

Note that this only sets the background colour...

If you want to change the button's look:

[myButton setBackgroundImage:[UIImage imageNamed:@"MyImage.png"] forState:UIControlStateNormal];

You can change the state to whichever state you like.

EDIT: If you are adding the button from interface builder, make sure to change the button Type to Custom, and change the image.

like image 135
Chris Cooper Avatar answered Nov 26 '25 09:11

Chris Cooper


This is how I got it done.

  1. In the .h file declare yourButton as an IBOutlet.

      @property (weak, nonatomic) IBOutlet UIButton *yourButton;
    
  2. In the .m file where you want to change the colour of the button use either

    [yourButton setBackgroundColor:[UIColor blueColor]];
    

or

[yourButton setBackgroundColor:[UIColor colorWithRed:0.80 green:0.80 blue:0.80 alpha:1.0]];

To obtain the colours I require I use this link.

like image 22
Ishara Amarasekera Avatar answered Nov 26 '25 11:11

Ishara Amarasekera