I’m trying to cycle backwards through an array by clicking a button.
My current code is close, but doesn’t quite work.
- (void)viewDidLoad {
self.imageNames = [NSArray arrayWithObjects:@"MyFirstImage", @"AnotherImage", nil];
currentImageIndex = 0;
[super viewDidLoad];
}
…what works:
- (IBAction)change {
UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imageNames objectAtIndex:currentImageIndex] ofType:@"png"];
currentImageIndex++;
if (currentImageIndex >= imageNames.count) {
currentImageIndex = 0;
}
}
…and what isn’t working:
- (IBAction)changeBack {
UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imageNames objectAtIndex:currentImageIndex] ofType:@"png"];
currentImageIndex--;
if (currentImageIndex >= imageNames.count) {
currentImageIndex = 0;
}
}
Any help is gladly appreciated!
Thanks!
You need to change the index first, then get the image. When going backwards you need to reset the index to the maximum (count-1) when you go negative:
To move forward to the next image: