0

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:

Cœur
  • 37,241
  • 25
  • 195
  • 267
Vlad Z.
  • 3,401
  • 3
  • 32
  • 60

3 Answers3

3

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];
Antonio MG
  • 20,382
  • 3
  • 43
  • 62
  • 4
    you are creating multiple image views! The answer is not correct. Buy you can only access the last imageview in grassImage. You should still be able to call [self.view viewWithTag:100]; - [self.view viewWithTag:112]; and access every single one! – Nils Ziehn Oct 23 '13 at 13:18
0

Use this code for getting subview with a particular tag,

UIImageView *imgViewRef = (UIImageView *)[self.view viewWithTag:TAG_NUMBER];
Amar
  • 13,202
  • 7
  • 53
  • 71
StuartM
  • 6,743
  • 18
  • 84
  • 160
0

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);
        }
    }
Ramaraj T
  • 5,184
  • 4
  • 35
  • 68