如何以编程方式更改 UIButton 内的 UIImageView 的图像?
How to change image of UIImageView that is inside a UIButton programmatically?
我在 Tim 的 this 问答的帮助下创建了一个带有 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 上设置标签的方式。我从 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];
我在 Tim 的 this 问答的帮助下创建了一个带有 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 上设置标签的方式。我从 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];