0

I'm trying to add multiple UIImageView to a scrollView. The number of imageview differs. This number is read from a file.

So now I have to create UIImageView *imageView1,UIImageView *imageView2,UIImageView *imageView3 ... UIImageView *imageViewN.

How do I add the number to the end of *imageView(?)

Any help would be greatly appreciated

3 Answers 3

2

This cannot be done the way that you are thinking. What you should do is use a NSMutableArray like so:

NSMutableArray *imageViews = [[NSMutableArray alloc] init];
for(NSInteger i=0; i < 10; i++)
{
    UIImageView *currentImageView = [[UIImageView alloc] initWithFrame:CGRectMake((0 * (110 * i)), 0, 100, 100)];
    [currentImageView setImage:[UIImage imageNamed:@"test.png"]];
    [imageViews addObject:currentImageView];
}


//To reference the image views just call objectAtIndex
UIImageView *imageView1 = [imageViews objectAtIndex:0];
UIImageView *imageView2 = [imageViews objectAtIndex:1];

This also makes your code much more flexible.

Sign up to request clarification or add additional context in comments.

1 Comment

After [imageViews addObject:currentImageView]; add [myScrollView addSubView:imageViews];(optional) and [imageViews release]; if you don't use ARC
0

Add to above code fragment:

 NSString *imageName = [NSString stringWithFormat@"test_%d.png", i];
 [currentImageView setImage:[UIImage imageNamed:imageName]];

thus you can add UIImageViews with different images

Comments

0

For anyone who still search for this topics recently, this is the Swift 3 version to do what @Siddharthan wants:

    //you may give any Int value to these variables
    let Xposition = 19
    let Yposition = 19
    let imageWidth = 93
    let imageHeight = 128

    //create UIImageView object
    var curr_imageView = UIImageView()
    for i in 0 ..< images.count {
        if imageViews.isEmpty {
            curr_imageView = UIImageView.init(frame: CGRect(x: Xposition, y: Yposition, width: imageWidth, height: imageHeight))
        } else {
            curr_imageView = UIImageView.init(frame: CGRect(x: Int(imageViews[i-1].frame.origin.x)+Int(imageViews[i-1].frame.size.width), y: Yposition, width: imageWidth, height: imageHeight))
        }

        curr_imageView.image = UIImage(named: images[i])
        curr_imageView.contentMode = .scaleAspectFit
        self.scrollView1.addSubview(curr_imageView)
        imageViews.append(curr_imageView)
    }

    self.scrollView1.contentSize = CGSize(width: imageViews[imageViews.count-1].frame.size.width+imageViews[imageViews.count-1].frame.origin.x+CGFloat(Xposition), height: self.scrollView1.frame.size.height)

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.