2012-10-06 91 views
0

我正在編程一個在不同視圖中有幾個UIImage動畫的應用程序。現在我使用這行代碼來加載所有圖像:輕鬆加載動畫

[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]], 

並加載所有這100個圖像。

然後,在第二視圖中,我加載它喜歡這些:

[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]], 

和再次加載100個圖像。

有沒有什麼方法可以加載所有的圖像,但只放一次圖像的名稱?我想要的是,例如,把前兩個數字(10),然後自動加載其餘的圖像。在Xcode中可能嗎?謝謝!

回答

1

這應該工作(未經測試,但這個想法應該清楚)

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

示例:NSArray *images = [self loadImagesWithNumber:1000 count:100];,這將加載100個圖像與1000.png開始1099.png

請記住,如果您有像0000.png0099.png的圖像,則這不起作用,因爲代碼不會添加任何前導零。但是如果你需要的話,這是微不足道的(隨時詢問你是否需要幫助)

+1

stringWithFormat:%@「%u.png」 - > stringWithFormat:@「%u.png」no? :) – bs7

+0

好thnaks,我會試試看。 – joan2404

+0

@ bs7哎呀,你是對的!修復。 – JustSid