views:

2257

answers:

2

This animates the UIImageView in the impactdrawarray:

if ( ((impact *) [impactarray objectAtIndex:iv]).animframe == 70){
   ((UIImageView *) [impactdrawarray objectAtIndex:iv]).image =
          [UIImage imageWithContentsOfFile:
                         [[NSBundle mainBundle] pathForResource:@"explosionA71"
                                                         ofType:@"png"]];
}
if ( ((impact *) [impactarray objectAtIndex:iv]).animframe == 71){
       ((UIImageView *) [impactdrawarray objectAtIndex:iv]).image =
                       [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] 
                                        pathForResource:@"explosionA72"
                                                 ofType:@"png"]];
}

Nothing appears with this:

NSString *myString2 =
           [NSString stringWithFormat:@"A%d",
                     ((impact *) [impactarray objectAtIndex:iv]).animframe;

((UIImageView *) [impactdrawarray objectAtIndex:iv]).image =
                    [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] 
                                     pathForResource:(@"explosion%d", myString2)
                                              ofType:@"png"]];

My reference for using NSString (example)

NSString *myString23 = [NSString stringWithFormat:@"$%d", money];
moneylabel.text = myString23;

How can I use a variable in the file name? Is there a way to load an image in a resource folder by index? something like imageByIndex:currentanimationframe? I didn't see anything in the UIImage documentation.

Response to comments:

   NSString *myString2 = [NSString stringWithFormat:@"A%d", ((impact *) [impactarray objectAtIndex:iv]).animframe];
  ((UIImageView *) [impactdrawarray objectAtIndex:iv]).image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"explosion%d", myString2] ofType:@"png"]];

and

    NSString *imagename = [NSString stringWithFormat:@"A%d", ((impact *) [impactarray objectAtIndex:iv]).animframe];
    UIImage *myImage = [UIImage imageNamed:imagename];

    ((UIImageView *) [impactdrawarray objectAtIndex:iv]).image = myImage;

Both compile and run, but the image does not show.

A: 
NSString* imageName = [self dynamicallyCalculateImageNameUsingCrazyMath];
UIImage* myImage = [UIImage imageNamed:imageName];
slf
+1  A: 

Use +stringWithFormat:, just as in your example:

[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"explosion%d", myString2] ofType:@"png"];
Jim Puls
NSString *myString2 = [NSString stringWithFormat:@"A%d", ((impact *) [impactarray objectAtIndex:iv]).animframe]; ((UIImageView *) [impactdrawarray objectAtIndex:iv]).image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"explosion%d", myString2] ofType:@"png"]];Still nothing shows up (still compiles OK)