Reputation: 21
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
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
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
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
Reputation: 185661
You can use +[NSString stringWithFormat:]
to construct the name, as in
img = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", infoInt]];
Upvotes: 2