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:

3
  • 3
    You don't need the property declaration at all to use this. Commented Oct 23, 2013 at 13:16
  • How do you "access this image views using tag"? Commented Oct 23, 2013 at 13:21
  • just get using this. UIImageView *imgViewRef = (UIImageView *)[self.view viewWithTag:TAG_NUMBER]; Commented Oct 23, 2013 at 13:23

3 Answers 3

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];
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

0

Use this code for getting subview with a particular tag,

UIImageView *imgViewRef = (UIImageView *)[self.view viewWithTag:TAG_NUMBER];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.