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

我有这个:

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];

但不知道什么会为它设置图像。


当前回答

Swift 3版本(butt_img必须是Image Set into Assets。xcassets或图像。xcassets文件夹在Xcode):

btnTwo.setBackgroundImage(UIImage(named: "butt_img"), for: .normal)
btnTwo.setTitle("My title", for: .normal)

无论如何,如果你想让图像缩放到按钮的大小,你可以在它上面添加一个UIImageView,并给它分配你的图像:

let img = UIImageView()
img.frame = btnTwo.frame
img.contentMode = .scaleAspectFill
img.clipsToBounds = true
img.image = UIImage(named: "butt_img")
btnTwo.addSubview(img)

其他回答

objective - c

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

斯威夫特5.1

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

在这之前,我必须根据图像帧大小显式地调整按钮帧的大小。

UIImage *listImage = [UIImage imageNamed:@"list_icon.png"];
UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom];

// get the image size and apply it to the button frame
CGRect listButtonFrame = listButton.frame;
listButtonFrame.size = listImage.size;
listButton.frame = listButtonFrame;

[listButton setImage:listImage forState:UIControlStateNormal];
[listButton addTarget:self.navigationController.parentViewController 
               action:@selector(revealToggle:) 
     forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton = 
  [[UIBarButtonItem alloc] initWithCustomView:listButton];

self.navigationItem.leftBarButtonItem = jobsButton;

你可以这样做

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

swift 5+

let image = UIImage(named: "icons-multiply")?.withRenderingMode(.alwaysTemplate)
btn.setImage(image, for: .normal)
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 150, 44);
[btn setBackgroundImage:[UIImage imageNamed:@"buttonimage.png"] 
               forState:UIControlStateNormal];
[btn addTarget:self 
     action:@selector(btnSendComment_pressed:) 
     forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];