Reputation: 3137
Hi I’m trying to get an image to change on a method call and if the method is recalled the original image comes back
-(void)change
{
if ((player.image = [UIImage imageNamed:@"first.png"]))
{
player.image = [UIImage imageNamed:@"second.png"]));
}
else
{
player.image = [UIImage imageNamed:@"first.png"]));
}
}
This works change the "first.png" image to "second.png" but when called again it doesn’t.
Where am I going wrong?
Upvotes: 0
Views: 53
Reputation: 5616
As pointed out by Michael Dautermann, the way you're comparing two UIImages is wrong. Can't you simply keep an NSString property that tells you the image you're showing?
-(void)change
{
if ([self.displayedImageTitle isEqualToString:@"first.png"]){
player.image = [UIImage imageNamed:@"second.png"]));
self.displayedImageTitle = @"second.png";
}
else{
player.image = [UIImage imageNamed:@"first.png"]));
self.displayedImageTitle = @"first.png";
}
}
Upvotes: 2
Reputation: 89509
In your code above, you're making an invalid assumption that "[UIImage imageNamed: @"first.png"]
" will always be the same UIImage object when you do a comparison. That isn't true. Every time you call the "imageNamed
" API, you may be creating a brand new UIImage object.
Now, since UIImage object doesn't know anything about file names or image titles, you need to keep track of which image is being displayed and then toggle on that.
I'd suggest creating a subclassed UIImage object that has a filename or title property (that you would also need to set), or have your two UIImages as properties or ivars loaded into memory (that is, if these aren't giant memory hogging images) and then do your toggling.
Upvotes: 0