如何以编程方式更改UIButton内的UIImageView的图像? [英] How to change image of UIImageView that is inside a UIButton programmatically?

查看:46
本文介绍了如何以编程方式更改UIButton内的UIImageView的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我借助

I created a UIButton with UIImageView and UILabel by the help of this question and answer by Tim and now I want change the image of the UIImageView on the button click event. I tried [sender.imageView setImage:image] but it not working

推荐答案

您可以:

1-在viewController的UIButton内保留对UIImageView的引用

1 - keep a reference to the UIImageView inside the UIButton on your viewController

2-子类化UIButton并自己添加UIImageView.

2 - Subclass the UIButton and add the UIImageView yourself.

3-添加UIImageView时,在其中添加一个标签(view.tag),从发送方获取视图时,您只需

3 - When adding the UIImageView, add a tag into it (view.tag) and when getting the view from the sender, you can just

UIView *view = (UIView *)sender;
UIImageView *imageView = [view viewWithTag:123];
//do what you must with the imageView.

标签可以是任何数字.

编辑

这是应该在UIImageView而不是UIButton上设置标签的方式.我从此处:

this is how you should set the tag on the UIImageView, and Not on the UIButton. I copied this code from Tim's answer from here:

// Create the button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

// Now load the image and create the image view
UIImage *image = [UIImage imageNamed:@"yourImage.png"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(/*frame*/)];
[imageView setImage:image];

// Create the label and set its text
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(/*frame*/)];
[label setText:@"Your title"];

// Set a tag on the UIImageView so you can get it later
imageView.tag = 123;

// Put it all together
[button addSubview:label];
[button addSubview:imageView];

这篇关于如何以编程方式更改UIButton内的UIImageView的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆