Reputation: 2809
I have a UIImageView object that I instantiate and turn into a property inside my iOS app. I initialize the attributes for this UIImageView object inside my viewDidLoad method, however, I need to change the image that is contained inside the UIImageView object later on in another method. When I do this, I for some reason am simply superimposing the new image over top of the old one. What I would like to do is simply resize the frame, and replace the old image with the new one.
Here is the relevant code:
Inside my viewDidLoad method:
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 250, 300, 200)];
imageView.image = [UIImage imageNamed:@"firstImage.png"];
[self.view addSubview:imageView];
and inside my method where I wish to make the changes:
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 250, 200, 300)];
imageView.image = [UIImage imageNamed:@"secondImage.png"];
[self.view addSubview:imageView];
Please bear in mind that I don't want to just change the image, but also the frame size to accommodate the new image. Can anyone see what I am doing wrong?
Upvotes: 1
Views: 1378
Reputation: 23278
You are creating another instance of imageview. You need to access the same object and change frame and image there.
Try this,
Create imageView
as property in the class as,
In .h file,
@property(nonatomic, retain) UIImageView *imageView;
Then in viewDidLoad
,
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 250, 300, 200)];
self.imageView.image = [UIImage imageNamed:@"firstImage.png"];
[self.view addSubview:imageView];
The in second method, just change the frame and image as shown below,
self.imageView.frame = CGRectMake(10, 250, 200, 300);
self.imageView.image = [UIImage imageNamed:@"secondImage.png"];
As per you code, you were creating separate instances for imageViews and adding as subviews which will cause it to superimpose on another one. Instead you need to create a single instance as shown above and modify its frame and image properties whenever required.
Upvotes: 3