如何在代码中设置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];

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


当前回答

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)

其他回答

不用太担心从代码中构造按钮,你可以在故事板中完成。这对我很管用,一句台词……更简单。

[self.button setBackgroundImage:[UIImage imageNamed: @"yourPic.png"] forState:UIControlStateNormal];

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)

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

如果是Swift用户

// case of normal image
let image1 = UIImage(named: "your_image_file_name_without_extension")!
button1.setImage(image1, forState: UIControlState.Normal) 

// in case you don't want image to change when "clicked", you can leave code below
// case of when button is clicked
let image2 = UIImage(named: "image_clicked")!
button1.setImage(image2, forState: UIControlState.Highlight)