开发者

Image Array IBAction to view next image in the array

Thanks to @JFoulkes I have got my app to show the first image in the array when clicking the next button. However, when I click it again, it does not show the next image in the array. This leads me to believe my IBAction for the next button is not quite right.

Here's the code I have so far...

In my .h file I have declared:

IBOutlet UIImageView *imageView;
NSArray *imageArray;
NSInteger currentImage;

And I also added:

-(IBAction) next;

In the .m file I have:

-(void) viewDidLoad;
{
imageArray = [[NSArray arrayWithObjects: 
                [UIImage imageNamed:@"1.png"], 
                  [UIImage imageNamed:@"2.png"], 
                  nil] retain];
}

This is my IBAction which is only ever showin开发者_如何学编程g the first image in the array (1.png) and when clicked again doesn't change the UIImageView to the second array image (2.png):

-(IBAction)next {

 if (currentImage + 1 == [imageArray count])
        currentImage = 0;
    UIImage *img = [imageArray objectAtIndex:currentImage];
    [imageView setImage:img]; 
   currentImage++;
}

Based on the code, how can I change the IBAction to successully iterate through the images in the array after ever click?


Your incrementing logic is broken, so the first click will do nothing and you can never reach the last image. If you would add a 3.png to your array, this would be a little more obvious. It might be instructive to step through the code, watching what it does at each step.

Correct incrementing logic would look something like this:

- (void)next {
    currentImage++;
    if (currentImage >= imageArray.count) currentImage = 0;
    UIImage *img = [imageArray objectAtIndex:currentImage];
    [imageView setImage:img];
}


You need to remove

currentImage = 0;

This means the first image will always be loaded

You need to add a check to see if currentImage is larger than the imagearray:

if (currentImage +1 < [imageArray count])
{
    currentImage++;
    UIImage *img = [imageArray objectAtIndex:currentImage];
    [imageView setImage:img]; 
}


Create an array of images name it as images, initialize an integer "i".
In the view, create an imageView and two buttons(next and previous),
Use this code for the button action,

-(void)nextButton:(id)sender
{
if (i < (array.count-1))
{
    i=i+1;
     imageView.image = [images objectAtIndex:i];
}
}

-(void)previousButton:(id)sender
{
if(i >= 1)
{
    i=i-1;
    imageView.image=[images objectAtIndex:i];
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜