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

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


当前回答

Mike的解决方案将只显示图像,但在按钮上设置的任何标题都将不可见,因为您可以设置标题或图像。

如果你想同时设置(你的图片和标题),请使用以下代码:

btnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal];
[btnTwo setTitle:@"Title" forState:UIControlStateNormal];

其他回答

swift 5+

let image = UIImage(named: "icons-multiply")?.withRenderingMode(.alwaysTemplate)
btn.setImage(image, 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;

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)
-(void)buttonTouched:(id)sender
{
    UIButton *btn = (UIButton *)sender;

    if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"icon-Locked.png"]])
    {
        [btn setImage:[UIImage imageNamed:@"icon-Unlocked.png"] forState:UIControlStateNormal];
        // other statements....
    }
    else
    {
        [btn setImage:[UIImage imageNamed:@"icon-Locked.png"] forState:UIControlStateNormal];
        // other statements....
    }
}