在代码中为UIButton设置图像

问题描述:

如何在代码中为UIButton设置图像?

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

我有:

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.

Objective-C

Objective-C

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

Swift 4

let btnImage = UIImage(named: "image")
btnTwo.setImage(btnImage , for: UIControlState.normal)