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

主宰稳场 提交于 2019-12-25 02:45:05

问题


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:


you can:

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

2 - Subclass the UIButton and add the UIImageView yourself.

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.

The tag can be any number.

Edit

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


来源:https://stackoverflow.com/questions/30577908/how-to-change-image-of-uiimageview-that-is-inside-a-uibutton-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!