在代码中为UIButton设置图像

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

但看不到将为其设置图像的内容。


拉莫斯之舞
浏览 651回答 3
3回答

月关宝盒

目标CUIImage *btnImage = [UIImage imageNamed:@"image.png"];[btnTwo setImage:btnImage forState:UIControlStateNormal];斯威夫特4let btnImage = UIImage(named: "image")btnTwo.setImage(btnImage , for: UIControlState.normal)

叮当猫咪

Mike的解决方案将仅显示图像,但是在按钮上设置的任何标题将不可见,因为您可以设置标题或图像。如果要同时设置(您的图像和标题),请使用以下代码:btnImage = [UIImage imageNamed:@"image.png"];[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal];[btnTwo setTitle:@"Title" forState:UIControlStateNormal];

蝴蝶不菲

在此之前,我必须根据图像帧的大小显式调整按钮帧的大小。UIImage *listImage = [UIImage imageNamed:@"list_icon.png"];UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom];// get the image size and apply it to the button frameCGRect 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;
打开App,查看更多内容
随时随地看视频慕课网APP