Adrian Farfan
Adrian Farfan

Reputation: 21

using integer variable to image name in ios

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];
}

Upvotes: 1

Views: 469

Answers (4)

Midhun MP
Midhun MP

Reputation: 107121

Use:

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

Also refer NSString Class Reference for more string functions.

Upvotes: 0

ask4asif
ask4asif

Reputation: 676

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

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

Upvotes: 0

P.J
P.J

Reputation: 6587

Change this line

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

to

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

Hope it helps you

Upvotes: 0

Lily Ballard
Lily Ballard

Reputation: 185661

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

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

Upvotes: 2

Related Questions