我有一个简单的for循环,可以在一组9个UIImageViews中更改图像。但是,我有一个问题,我无法在for循环的协调中更改UIImageView的名称,因此最终结果是for循环仅影响我在iOS App中的9个UIImageViews中的1个。 / p>
这是我的代码:
for (current_photo = 1; current_photo < 10; current_photo++) {
picview_1.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%i.png", SERVER_URL, current_photo]];
}
您会注意到我的代码中有一点:
picview_1.image
当我更换“picview_current_photo”的“pic view_1”时,会出现错误。
我做错了什么?请解释。
感谢您的时间:)
答案 0 :(得分:2)
创建一个UIImageView
的数组,并通过索引循环访问它们,如下所示:
NSArray *imageViews = @[picview_1, picview_2, picview_3, picview_4, ..., picview_9];
// Arrays are indexed from zero, so I changed the index to run from 0 to 9
for (current_photo = 0; current_photo < 9; current_photo++) {
// Since current_photo is zero-based, I added one to it in stringWithFormat
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"%@%i.png", SERVER_URL, current_photo+1]];
[[imageViews objectAtIndex:current_photo] setImage:img];
}
答案 1 :(得分:0)
最好设置一个UIImageViews数组。然后从该阵列访问所需的UIImageView并根据需要设置图像。