Objective c 有没有办法将同一图像设置为多个UIImageView?

Objective c 有没有办法将同一图像设置为多个UIImageView?,objective-c,uiimageview,Objective C,Uiimageview,我正在使用一个图像密集型iOS应用程序,我发现自己一次又一次地输入几乎相同的行: ... A016.image = [UIImage imageNamed:img21]; A017.image = [UIImage imageNamed:img21]; A018.image = [UIImage imageNamed:img21]; ... 现在我问你:有没有一种方法可以将UIImageViews名称存储在数组或其他什么东西中? 只是为了美化我丑陋的代码。 /John是的,您可以将UIImag

我正在使用一个图像密集型iOS应用程序,我发现自己一次又一次地输入几乎相同的行:

...
A016.image = [UIImage imageNamed:img21];
A017.image = [UIImage imageNamed:img21];
A018.image = [UIImage imageNamed:img21];
...
现在我问你:有没有一种方法可以将UIImageViews名称存储在数组或其他什么东西中? 只是为了美化我丑陋的代码。
/John

是的,您可以将UIImageViews放入数组中,然后将其放入for

UIImageView * imageView1;
UIImageView * imageView2;
UIImageView * imageView3;
NSArray * imageViewsArray = [NSArray arrayWithObjects:imageView1,imageView2,imageView3,nil];

for (UIImageView * currentImageView in imageViewsArray) {

     currentImageView.image = [UIImage imageNamed:img21];

}

当然,你可以简化这样的事情。但具体的情况并不完全清楚

如果所有图像视图都在一个数组中,则可以执行类似操作

// Assume an NSArray called imageViews exists with all the UIImageView instances in it.
for (UIImageView *imageView in imageViews) {
    imageView.image = [UIImage imageNamed:img21];
}
NSMutableArray *imageViews = [NSMutableArray arrayWithCapacity:20];
for (int i = 0; i < 20; i++) {
    NSString *variableName = [NSString stringWithFormat:@"A0%d", i];
    UIImageView *imageView = [self valueForKey:variableName];
    [imageViews addObject:imageView];
}
如果您的图像视图不在数组中,并且实际上被称为A016、A017等,那么我建议您更改代码设计。像这样的事情从来都不是个好主意。它会导致糟糕的、难以维护的代码。如果这是某种类型的图像表,请首先尝试将图像视图放入数组中

也就是说,有很多方法可以将这样的变量放入数组中。如果它们被声明为@properties或ivar,您可以这样做

// Assume an NSArray called imageViews exists with all the UIImageView instances in it.
for (UIImageView *imageView in imageViews) {
    imageView.image = [UIImage imageNamed:img21];
}
NSMutableArray *imageViews = [NSMutableArray arrayWithCapacity:20];
for (int i = 0; i < 20; i++) {
    NSString *variableName = [NSString stringWithFormat:@"A0%d", i];
    UIImageView *imageView = [self valueForKey:variableName];
    [imageViews addObject:imageView];
}

但是我真的建议不要使用那样的索引变量名。

@jcear非常感谢!这正是我的目标@约翰维兰德,你有什么理由不接受答案吗?谢谢你的教学性回答。非常容易阅读和遵循!谢谢!