我知道我可以这样做:
switch (imageNumber) {
case 1: image1.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"jpg"]]; break;
case 2: image2.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"jpg"]]; break;
case 3: image3.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"jpg"]]; break;
case 4: image4.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"jpg"]]; break;
}
我想在我的代码中更有效率,所以我想知道是否有办法这样做:
switch (imageNumber) {
case 1: //somehow set image1 as the imageView I want used
case 2: //somehow set image2 as the imageView I want used
case 3: //somehow set image3 as the imageView I want used
case 4: //somehow set image4 as the imageView I want used
}
imageWhicheverWasSet.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"jpg"]];
提前感谢您的帮助!
答案 0 :(得分:1)
您自己粘贴的第二个代码段实际上非常接近解决方案。您只需将UIImageView *imageToChange;
设置为实例变量,然后执行:
imageToChange.image = nil; // will clear the image on last selected image view
// if you don't need that, just remove that line and leave others
switch (imageNumber) {
case 1: imageToChange = image1; break;
case 2: imageToChange = image2; break;
case 3: imageToChange = image3; break;
case 4: imageToChange = image4; break;
}
imageToChange.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"jpg"]];
答案 1 :(得分:1)
您可以将UIImageViews放在一个数组中,然后使用索引选择正确的索引。除非你有更多的UIImageViews要处理,否则不确定这会有用。
NSArray* imageViews = [NSArray arrayWithObjects: image1, image2, image3, image4, nil];
UIImageView* theImage = [imageViews objectAtIndex: imageNumber-1];
UIImage* theImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"jpg"]];
您需要验证imageNumber
以确保它在范围内。
答案 2 :(得分:0)
怎么样 -
UIImage* theImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"jpg"]];
switch ...
case 1:image1.image = theImage; break;
case 2:...
你也可以 -
MyImageType* tempImageObj = nil;
switch ... {
case 1:tempImageObj = &image1; break; // Or just image1, if ".image" is a property, not a field
case 2:...
}
tempImageObj ->image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"jpg"]]; // Or "." instead of "->" if property.
答案 3 :(得分:0)
另一种方法是使用数组
UIImageView *iv[] = {
image1,
image2,
image3,
image4,
};
if (imageNumber>=0 && imageNumber<4)
iv[imageNumber].image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:@"imageName"
ofType:@"jpg"]]