1

I have a simple for loop which changes the images in a set of 9 UIImageViews. However, I have one problem, I can't change the name of the UIImageView in co-ordination of the for loop and so the end result is that the for loop ONLY affects 1 out of 9 UIImageViews I have in my iOS App.

Here is my code:

for (current_photo = 1; current_photo < 10; current_photo++) {
        picview_1.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%i.png", SERVER_URL, current_photo]];
    }

You will notice that in my code there is a bit:

picview_1.image

When I replace the "pic view_1" which "picview_current_photo", it comes up with errors.

What am I doing wrong? Please explain.

Thanks for your time :)

2 Answers 2

2

Create an array of UIImageViews, and access them in a loop through an index, like this:

NSArray *imageViews = @[picview_1, picview_2, picview_3, picview_4, ..., picview_9];
// Arrays are indexed from zero, so I changed the index to run from 0 to 9
for (current_photo = 0; current_photo < 9; current_photo++) {
    // Since current_photo is zero-based, I added one to it in stringWithFormat
    UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"%@%i.png", SERVER_URL, current_photo+1]];
    [[imageViews objectAtIndex:current_photo] setImage:img];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Superb solution. And I'm still a beginner programmer so using an Array didn't come to mind.
0

You are probably best to set up an array of UIImageViews. Then access the UIImageView that you need from that array and set the image as required.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.