Alex Rivera | Logout

Setting an image for a UIButton in code

Asked 2009-09-24T02:06:31.210
215

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.

Edit
Report

2 Answers

431

Objective-C

UIImage *btnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setImage:btnImage forState:UIControlStateNormal];

Swift 5.1

let btnImage = UIImage(named: "image")
btnTwo.setImage(btnImage , for: .normal)
answered 2009-09-24T02:16:33.233
10

You can do it like this

[btnTwo setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
answered 2012-11-07T10:33:55.647

Your Answer