Spanky Spanky - 1 year ago 137
iOS Question

Setting an image for a UIButton in code

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.

Answer Source


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


let btnImage = UIImage(named: "image")
btnTwo.setImage(btnImage , forState: UIControlState.Normal)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download