I want to create multiple UIImageViews programmatically with different tags and add them as subview of my main view.

I have a property of my UIImageView in header:

@property (strong, nonatomic) UIImageView *grassImage;

then i'm trying to create multiple views:

for (int i=0;i<13;i++){

        grassImage = [[UIImageView alloc] init];

        int randNum = arc4random() % 320; //create random number for x position.

        [grassImage setFrame:CGRectMake(randNum, 200.0, 50.0, 25.0)];
        [grassImage setTag:i+100];
        [grassImage setImage:[UIImage imageNamed:@"grass"]];

        [self.view addSubview:grassImage];
    }

But when I'm trying to access this image views using tag, I'm getting only last tag - 112.

My question - how I can access this views correctly, using their tag?

Similar questions:

有帮助吗?

解决方案

You are only getting the last one because you are recreating the same view all the time.

Get rid of that variable, and add your views like this:

for (int i=0;i<13;i++){
    UIImageView *grassImage = [[UIImageView alloc] init];

    int randNum = arc4random() % 320; //create random number for x position.

    [grassImage setFrame:CGRectMake(randNum, 200.0, 50.0, 25.0)];
    [grassImage setTag:i+100];
    [grassImage setImage:[UIImage imageNamed:@"grass"]];

    [self.view addSubview:grassImage];
}

And to get the views:

UIImageView *imgView = [self.view viewWithTag:110];

其他提示

Since you are re-creating the same image again and again, if you access grassImage it will give you the last imageview you created. Instead you can get the imageview like this.

 for (UIImageView *imgView in self.view.subviews) {
        if ([imgView isKindOfClass:[UIImageView class]]) {
            NSLog(@"imageview with tag %d found", imgView.tag);
        }
    }

Use this code for getting subview with a particular tag,

UIImageView *imgViewRef = (UIImageView *)[self.view viewWithTag:TAG_NUMBER];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top