Muhammad Ameen Sheikh
Muhammad Ameen Sheikh

Reputation: 422

Looping through an array of images

I want to loop through an array of images and display each image one by one on the click of a single button.

Here is my code.

This is in the viewDidLoad method:

    arrayImg = [[NSArray alloc]initWithObjects:
            [UIImage imageNamed:@"samsung_logo_small.jpg"],
            [UIImage imageNamed:@"Small_logo_splash.png"],
            [UIImage imageNamed:@"Red_logos_small.png"],
            [UIImage imageNamed:@"li-logo-small-drshdw.gif"],
            nil];

Here is my button in which I am looping through the images

- (IBAction)btn:(id)sender {
for (int i = 0 ; i < [arrayImg count]; i++) {
    [img setImage:[arrayImg objectAtIndex:i]];
}

}

The problem is that it is only showing the last image, not all of the images.

What I am doing wrong here?

I found 2 questions like this on but could not find the answer.

Upvotes: 0

Views: 880

Answers (4)

Anon
Anon

Reputation: 623

Add following to YourClass.m file:

@interface YourClass() {
    int variableName;
}

@end

in viewDidLoad initialize variableName to 0.

- (IBAction)btn:(id)sender 
{
    if (variableName == arrayImg.count)
    {
        variableName = 0;
    }
    [img setImage:[arrayImg objectAtIndex:classVariable]];
    variableName++
}

Upvotes: 3

Mrunal
Mrunal

Reputation: 14118

In your viewDidLoad, add one more line:

[buttonName setTag:0];

Here change in btn event:

- (IBAction)btn:(UIButton *)sender {

   [img setImage: [arrayImg objectAtIndex: [sender tag]]];

   [sender setTag: [sender tag]+1];

   if ([sender tag] > [arrayImg count]) {
     [sender setTag: 0];
   }
}

This will help you in memory management as well, because here no other extra flag variable required to hold your integer value, whereas your UIButton object only will hold.

Hope this will help you to achieve your requirement.

Upvotes: 1

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

If you want to show one image at a time then why loop? You can do it like this:

 static int index;

- (IBAction)btn:(id)sender {

  [img setImage:[arrayImg objectAtIndex:index]];
   index = index == arrayImg.count - 1 ? 0 : index + 1;
}

Upvotes: 2

Gordonium
Gordonium

Reputation: 3487

From what I can tell, you're looping through all of the images on a single click.

A better approach might be to display an image after a click but instead of looping just increment a variable that represents your index value by 1. This way after each click the next image is displayed.

The other approach would be to use a timer.

[NSTimer scheduledTimerWithTimeInterval:2.0
                                 target:self
                               selector:@selector(displayNextImage:)
                               userInfo:nil
                                repeats:YES];

Upvotes: 0

Related Questions