我可以自动创建UIImageView的实例吗?

Jad*_*ift 1 iphone objective-c ipad ios

现在我创建如下(我的file.h):

UIImageView *pic1, *pic2, *pic3, *pic4, *pic5, *pic6, *pic7, *pic8, *pic9, *pic10;

Then in my (file.m):

UIImageView *pic1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”picName.png”]];

UIImageView *pic2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”picName.png”]];
……

UIImageView *pic10 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”picName.png”]];
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我需要UIImageView的许多实例(由其他因素触发的数字).

有没有办法在我的file.m中自动创建多个UIImageView实例,不知何故如下?:

for (int x; (x=10); x++)
{
    UIImageView * pic[x] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myPic.png"]];
}
Run Code Online (Sandbox Code Playgroud)

这个例子不起作用,但我想展示我想要编程的内容.

das*_*ght 6

当然你可以 - 这就是数组的用途:

NSMutableArray *pics = [NSMutableArray array];
for (int i = 0 ; i != 10 ; i++) {
    [pics addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myPic.png"]]];
}
Run Code Online (Sandbox Code Playgroud)

如果图片的名称取决于索引,请使用NSString's stringWithFormat来生成图片的名称 - 例如,您可以这样做:

NSMutableArray *pics = [NSMutableArray array];
for (int i = 0 ; i != 10 ; i++) {
    NSString *imgName = [NSString stringWithFormat:@"myPic%d.png"];
    [pics addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:imgName]]];
}
Run Code Online (Sandbox Code Playgroud)