Search code examples
iosiphoneobjective-cuiimageviewprogrammatically-created

Create multiple UIImageViews programmatically


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:


Solution

  • 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];