繁体   English   中英

如何以编程方式更改UIButton内的UIImageView的图像?

[英]How to change image of UIImageView that is inside a UIButton programmatically?

问题和解答(由Tim回答)的帮助下,我使用UIImageView和UILabel创建了一个UIButton,现在我想在按钮单击事件上更改UIImageView的图像。 我试过了[sender.imageView setImage:image]但它不起作用

您可以:

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

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

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

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

标签可以是任何数字。

编辑

这就是您应该在UIImageView而不是UIButton上设置标签的方式。 我从这里的蒂姆的答案中复制了这段代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM