hyekyung
hyekyung

Reputation: 671

How to select UIImageView with name of Object

I added 6 UIImageViews in Interface Builder. Those are declared.

@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;

Those UIImageView' name has a rule - "Image" + number.

I want to select those ImageViews dinamically. For example,

for (NSInteger i = 0; i < 6 ; i++) {

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

}

But, this code isn't correct. Please tell me more good way.

Upvotes: 0

Views: 868

Answers (3)

rob mayoff
rob mayoff

Reputation: 385860

jonkroll's suggestion to put your image views in an array is a good way to do it, and generally the highest performance.

Another way is to use key-value coding (KVC) to access your properties by name:

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

Using the view tag, as Mark suggests, is a third way to do it. His answer is a little short on details, so I will provide some.

You can set the tag in your nib:

Interface Builder with tag field circled

So you can set the tag of your Image1 image view to 1, and the tag of your Image2 image view to 2, and so on.

Then you can find an image view by its tag using the viewWithTag: method on your top-level view:

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

Upvotes: 2

jonkroll
jonkroll

Reputation: 15722

Create an array of your imageViews and iterate over them using fast enumeration:

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) 
    }
}

Upvotes: 1

Mark
Mark

Reputation: 509

typically you can use Tag to identify your views, instead of using the name of the view.

@property(nonatomic) NSInteger tag

see here:

https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIView_Class/UIView/UIView.html

once you've set the tag, you can then do things like if(uiview.tag == kSomeButtonTag)

Upvotes: 0

Related Questions