Add multiple image in same UIImageView and change them at each tap

53 views Asked by At

I'm trying to implement a UIImageView that shows different .png (organized in a NSArray) at each tap. When the tap reaches the last .png, the next tap will show the first .png and so on. I found an old answer here: Add 4 image in imageview and change the picture with tap or swipe gesture that seems to go in the right direction. However, it doesn't seem to be applicable in the new XCode and there is no more possibility to ask clarifications or updates since the topic has been closed. Does anybody have an idea on how to subclass then entire ImageView to get the expected result?

1

There are 1 answers

0
Stefano On BEST ANSWER

The solution was much easier than I thought.

As a custom value to the selector cannot be passed in the way I asked, I created an helper property that holds the index of the currently displayed image, increment that on every tap and set the image accordingly.

@interface YourViewController ()

@property (nonatomic, strong) NSArray *images;
@property (nonatomic, assign) NSInteger currentImageIndex;

@end


@implementation YourViewController

- (void)viewDidLoad {

// Here you fill your images array
self.images = ...   

//  Set currentImageIndex to 0 and display first image 
self.currentImageIndex = 0;
[self displayImageWithIndex:self.currentImageIndex];

// Additional code, like your button target/action
}
- (void)myButtonWasTapped:(id)sender
{
if(self.currentImageIndex + 1 < [self.images count]) {
    self.currentImageIndex++;
} else {
    self.currentImageIndex = 0;
}
[self displayImageWithIndex: self.currentImageIndex];
}

- (void)displayImageWithIndex:(NSInteger)index {
self.imageView.image = [self.images objectAtIndex:index];
}

@end

Please note: there might be a better approach to this, but this is what it worked in my case. Hope this can be helpful.