Varun Naharia
Varun Naharia

Reputation: 5420

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

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

Upvotes: 0

Views: 1569

Answers (1)

Erakk
Erakk

Reputation: 922

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

Upvotes: 2

Related Questions