1

I need to create a certain number of UIImageViews based on the amount of objects inside of an NSMutableArray. For example, if there are 5 UIImage's inside of this NSMutableArray, how do I create 5 UIImageView's with those images?

Thanks

2 Answers 2

1

Use count property of NSArray:

UIImage *image1 = [UIImage imageNamed:@"img1.png"];
UIImage *image2 = [UIImage imageNamed:@"img2.png"];
UIImage *image3 = [UIImage imageNamed:@"img3.png"];
UIImage *image4 = [UIImage imageNamed:@"img4.png"];
UIImage *image5 = [UIImage imageNamed:@"img5.png"];
NSArray *imageArray = @[image1, image2, image3, image4, image5];

NSInteger imageCount = 0;
NSInteger imageViewYM = 20; // Ensure this is bigger than image height

for (UIImage *image in imageArray) {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, imageViewYM * imageCount, image.size.width, image.size.height)];
    imageView.image = image;

    [self.view addSubview:imageView];
    imageCount++;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I have set it up now. Do you know if there is a way to have them move across for each imageView instead of overlapping? Thanks again
The NSInteger holds count of UIImageView which use based on the context like setting the superview' frame etc. However the for loop is good enough to let you access UIImages for you to create your image views.
@Dyllan - Sorry but I didn't quite get your question. Can you please rephrase.
since there are multiple UIImageViews being created, how can I space between them? At the moment it is working but they overlap, I was wondering how i would go about spacing between them. Thanks again
Glad it helped :). Could you please accept this answer.
0

Run a while loop for all the images and create a new UIImageView for each of them:

NSArray *imageArray = @[image1, image2, image3];  
int i = 0;
while(i < imageArray.count) {
    UIImageView * imageView = [[UIImageView alloc] init];
    imageView.image = [imageArray objectAtIndex:i];
    imageView.frame = CGRectMake(0, 0, 50, 50);
    imageView.tag = i;
    [self.view addSubview:imageView];
    i++;
}

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.