为了账号安全,请及时绑定邮箱和手机立即绑定

在代码中为UIButton设置图像

在代码中为UIButton设置图像

拉莫斯之舞 2019-11-25 14:16:41
如何在代码中为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];但看不到将为其设置图像的内容。
查看完整描述

3 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

目标C


UIImage *btnImage = [UIImage imageNamed:@"image.png"];

[btnTwo setImage:btnImage forState:UIControlStateNormal];

斯威夫特4


let btnImage = UIImage(named: "image")

btnTwo.setImage(btnImage , for: UIControlState.normal)


查看完整回答
反对 回复 2019-11-25
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

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


如果要同时设置(您的图像和标题),请使用以下代码:


btnImage = [UIImage imageNamed:@"image.png"];

[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal];

[btnTwo setTitle:@"Title" forState:UIControlStateNormal];


查看完整回答
反对 回复 2019-11-25
?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

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


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;


查看完整回答
反对 回复 2019-11-25
  • 3 回答
  • 0 关注
  • 646 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信