2012-02-19 37 views
0

我在Interface Builder中添加了6个UIImageViews。 这些声明。如何选择名称为Object的UIImageView

@property(nonatomic,strong)IBOutlet UIImageView * Image1;

@property(nonatomic,strong)IBOutlet UIImageView * Image2;

@property(nonatomic,strong)IBOutlet UIImageView * Image3;

@property(nonatomic,strong)IBOutlet UIImageView * Image4;

@property(nonatomic,strong)IBOutlet UIImageView * Image5;

@property(nonatomic,strong)IBOutlet UIImageView * Image6;

那些UIImageView的名字有一个规则 - “图像”+数字。

我想选择这些ImageViews dinamically。 例如,

为(NSInteger的I = 0;我< 6;我++){

if(... condition) 
    { 
     //new 
     [[NSString stringWithFormat:@"Image%d", i+1] setHidden:YES]; //--(1) 
    } 
    else 
    { 
     [[NSString stringWithFormat:@"Image%d", i+1] setHidden:NO]; //--(2) 
    } 

} 

但是,这个代码是不正确的。 请告诉我更多好方法。

回答

2

jonkroll建议将图像视图放入数组中是一种很好的方法,而且通常是最高性能。

另一种方法是使用键 - 值编码(KVC)通过名称来访问属性:

for (int i = 0; i < 6; ++i) { 
    NSString *key = [NSString stringWithFormat:@"Image%d", i + 1]; 
    UIImageView *imageView = (UIImageView *)[self valueForKey:key]; 
    imageView.hidden = condition; 
} 

使用视图标签,马克指出,第三种办法做到这一点。他的回答在细节上有点不足,所以我会提供一些。

您可以设置标签在你的笔尖:

Interface Builder with tag field circled

所以,你可以设置你的Image1图像视图1的标记,且Image2图像视图2标签,等等。

然后你可以使用viewWithTag:方法对您的顶级视图中找到它的标签的形象图:

for (int i = 0; i < 6; ++i) { 
    [self.view viewWithTag:i+1].hidden = condition; 
} 
+0

非常感谢你,抢! :D – hyekyung 2012-02-19 08:07:11

+0

我喜欢第一种方式,键值编码。好的Rob Rob :) – Mrunal 2012-02-19 08:37:07

1

创建一个imageViews数组,并使用快速枚举遍历它们:

NSArray *imageViewArray = [NSArray arrayWithObjects:self.Image1,self.Image2,self.Image3,self.Image4,self.Image5,self.Image6,nil]; 

for (UIImageView* imageView in imageViewArray) { 

    if(... condition) { 
     [imageView setHidden:YES]; //--(1) 
    } else { 
     [imageView setHidden:NO]; //--(2) 
    } 
} 
+0

谢谢你的好意! ^^ * – hyekyung 2012-02-19 08:15:12