joan2404
joan2404

Reputation: 315

Load animations easily

I'm programming an app that has several UIImage animations in different views. Now i'm using this line of code to load all the images:

[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10001.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10002.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10003.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10004.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"10005.png" ofType:nil]],

and load all the 100 images like this.

And then, on the second view, I load it like these:

[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20001.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20002.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20003.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20004.png" ofType:nil]],
[UIImage    imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"20005.png" ofType:nil]],

and again load the 100 images.

Is there any way to load all the images but only putting the name of the image one time? What I would like is to, for example, put the first 2 numbers (10) and then load the rest of the images automatically. Is it possible in Xcode? Thanks!

Upvotes: 0

Views: 86

Answers (1)

JustSid
JustSid

Reputation: 25318

This should work (untested, but the idea should be clear)

- (NSArray *)loadImagesWithNumber:(NSInteger)number count:(NSUInteger)count
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];

    for(NSUInteger i=0; i<count; i++)
    {
        NSString *name = [NSString stringWithFormat:@"%u.png", number + i];
        UIImage *image = [UIImage imageNamed:name];

        [array addObject:image];
    }

    return array;
}

Example: NSArray *images = [self loadImagesWithNumber:1000 count:100];, this would load 100 images starting with 1000.png to 1099.png.

Keep in mind that this doesn't work if you have images like 0000.png to 0099.png because the code doesn't add any leading zeroes. But that's trivial to add if you need it (feel free to ask if you need help with it)

Upvotes: 1

Related Questions