1

I have a set of images named 0.png, 1.png, 2.png, etc...

Say I only have five. I want to use an integer variable (infoInt) to determine what image is displayed. Since I'm naming the images in numbers, I though I could define the image as what ever the integer was. i.e. infoInt.png (as infoInt changes). I'm not sure how I can approach it. Here is my attempt.

- (void)viewDidLoad{

[super viewDidLoad];
UIImage *img;

for (infoInt =0; infoInt<=5; infoInt++) {
    img = [UIImage imageNamed:infoInt".png"]; //What to do here? How do I use infoInt variable in image name?
    [imageView setImage:img];
}

4 Answers 4

2

You can use +[NSString stringWithFormat:] to construct the name, as in

img = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", infoInt]];
Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks, the code definitely makes sense. But all the images seem to be displaying the one image, where infoInt = 5. I was hoping it was going to assign an integer for each increment. Is there a way I can increment the integer after assigning infoInt to an image.
@AdrianFarfan: You're assigning all the images, in turn, to the same imageview. Of course it's going to end up only displaying the last one.
0

Change this line

img = [UIImage imageNamed:infoInt".png"];

to

img = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png",infoInt]];

Hope it helps you

Comments

0

You can use stringWithFormat and use the for loop counter to generate image name as

img = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", infoInt]];

Comments

0

Use:

NSString *fileName = [NSString stringWithFormat:@"%d.png", infoInt]
img = [UIImage imageNamed:fileName];

Also refer NSString Class Reference for more string functions.

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.