tags:

views:

46

answers:

2

Hello!

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!

A: 

Perhaps in the changeBack method, you should alter this line of code to show the following:

if (currentImageIndex <= 0) {
currentImageIndex = imageNames.count;
}

(This is assuming when the user gets past the first image, they go back to the last one)

Chromium
That crashes the app. Very odd.
dot
+1  A: 

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:

- (IBAction)changeBack {
    currentImageIndex--;
    if (currentImageIndex < 0) {    // was first image
        currentImageIndex = imageNames.count-1;  // last image 
    }

    UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imageNames objectAtIndex:currentImageIndex] ofType:@"png"];
}

To move forward to the next image:

- (IBAction)change {
    currentImageIndex++;
    if (currentImageIndex >= imageNames.count) {    // was last image
        currentImageIndex = 0;  // back to first image 
    }

    UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imageNames objectAtIndex:currentImageIndex] ofType:@"png"];
}
progrmr
thanks! That worked like a charm.
dot