【发布时间】:2015-08-15 04:08:59
【问题描述】:
在 Tim 的 this 问答的帮助下,我创建了一个带有 UIImageView 和 UILabel 的 UIButton,现在我想在按钮单击事件上更改 UIImageView 的图像。
我试过[sender.imageView setImage:image] 但它不起作用
【问题讨论】:
标签: ios objective-c iphone uiimageview uibutton
在 Tim 的 this 问答的帮助下,我创建了一个带有 UIImageView 和 UILabel 的 UIButton,现在我想在按钮单击事件上更改 UIImageView 的图像。
我试过[sender.imageView setImage:image] 但它不起作用
【问题讨论】:
标签: ios objective-c iphone uiimageview uibutton
你可以:
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 上。我从 here 的 Tim 的回答中复制了这段代码:
// 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];
【讨论】:
UIImageView *imageView = [button viewWithTag:123];不兼容的指针 UIImageView 与 UIView 类型崩溃