views:

2977

answers:

2

Hi,

How do you set the image for a UIButton in code?

I have this:

UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self action:@selector(goToOne) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnTwo];

but don't see what will set the image for it.

Any help appreciated, Thanks // :)

+3  A: 

Try something like:

btnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setImage:btnImage forState:UIControlStateNormal];
Mike W
Thanks, that works // :)
Spanky
As a sidenote: this will show the image, but the button title text will be hidden.
Colins
+2  A: 

Mike's solution will just show the image, but any title set on the button will not be visible, because you can either set the title or the image.

If you want to set both (your image and title) use the following code:

btnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal];
[btnTwo setTitle:@"Title" forState:UIControlStateNormal];
Colins