1

如何通过在 for 循环中执行来缩短以下代码?

NSArray *images = [NSArray arrayWithObjects:
                         [UIImage imageNamed:@"z1.png"],
                         [UIImage imageNamed:@"z2.png"],
                         [UIImage imageNamed:@"z3.png"],
                         [UIImage imageNamed:@"z4.png"],
                         [UIImage imageNamed:@"z5.png"],
                         [UIImage imageNamed:@"z6.png"],
                         [UIImage imageNamed:@"z7.png"],
                         [UIImage imageNamed:@"z8.png"],
                         [UIImage imageNamed:@"z9.png"],
                         [UIImage imageNamed:@"z10.png"],
                         [UIImage imageNamed:@"z11.png"],
                         [UIImage imageNamed:@"z12.png"],
                         [UIImage imageNamed:@"z13.png"],
                         [UIImage imageNamed:@"z14.png"],
                         [UIImage imageNamed:@"z15.png"],
                         [UIImage imageNamed:@"z16.png"],
                         [UIImage imageNamed:@"z17.png"],
                         [UIImage imageNamed:@"z18.png"],
                         [UIImage imageNamed:@"z19.png"],
                         nil];
4

6 回答 6

11

NSMutableArray正如评论中提到的@Teak 一样,魔法就在其中。事实上,所有容器类都有一个可变版本,比如NSString, NSDictionary,NSSet等。

NSMutableArray *images = [NSMutableArray array];

for (NSUInteger i = 1; i <= 19; i++) {
    NSString *imageName = [NSString stringWithFormat:@"z%d.png", i];
    [images addObject:[UIImage imageNamed:imageName];
}
于 2012-06-30T19:25:00.703 回答
4

如果您不介意停止动画,您可以从 iOS 5 开始执行以下操作:

UIImage *myAnimatedImage = [UIImage animatedImageNamed:@"z" duration:10];

它将自动搜索图像并为其添加数字。需要注意的是,您不能像在UIImageView.

于 2012-06-30T19:27:53.307 回答
2

您需要使用NSMutableArray. 但是,如果不变性很重要,您可以将结果放在NSArray末尾。

NSMutableArray *workingArray = [NSMutableArray array];
for (int i = 0; i < NUM_IMAGES; i++) {
    [workingArray addObject:[UIImage imageName:[NSString stringWithFormat:@"z%d.png", i]];
}

NSArray *images = [NSArray arrayWithArray:workingArray];
于 2012-06-30T19:26:30.327 回答
1
NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:19];

for(int i = 1; i <=19; i++)
    [images addObject:[UIImage imageNamed:[NSString stringWithFormat:@"z%d.png, i]]];
于 2012-06-30T19:25:56.180 回答
1
 NSMutableArray *arrImage = [NSMutableArray  arrayWithCapacity:0];
 for(int i = 1; i<= 19;i++)
 {
    [arrImage  addObject:[UIImage imageNamed:[NSString stringWithFormat:@"z%d.png",i]]];
 }
于 2012-06-30T19:27:03.680 回答
1

您加载一个动画 UIImage,它会为您处理文件名。然后你从中检索图像数组。

NSArray* images = [UIImage animatedImageNamed:@"z" duration:1].images;

于 2012-10-04T12:52:17.763 回答