views:

785

answers:

4

I would like to create a 4 x 6 grid of UIImageViews that each contain a slightly different image. I would also like to be able to randomly select one of the instances and change it's image.

My question is what's the best way to set up the UIImageViews in a grid formation, perform a few actions between each setup, and randomly pick 1 of the 24 instances once setup is complete. Optimally, I wouldn't have to set up each one by one.

Thanks in advance.

A: 

There are different approaches you can take, depending on whether or not you want to use Interface Builder to layout your grid.

One option is to layout your 24 UIImageViews as subviews of a common parent view within IB. On the View Attributes tab you can set a "Tag" number from 1 to 24 to differentiate your UIImageViews. Then in your code you can use [parentView viewWithTag:tagNumber] to access each UIImageView.

If you prefer to do things more programmatically, you could create each of your UIImageViews in a loop in the loadView method of your UIViewController subclass. You could maintain an array (or an array of arrays corresponding to rows and columns) as a property of your controller, and store a reference to each of these image views as you create them. For each UIImageView you create, set its imageView.frame property to define its position, then call [view addSubview:imageView] to add it to the parent view.

cduhn
A: 

Thanks for the response cduhn. So it appears that with either method I would still have to set each UIImageView's image property one by one. In the future I plan on increasing the grid size to say, 6 x 9 so I was hoping that there would be a faster, more automated approach.

Also, how would I handle the random picking of an instance?

Thanks.

Well, if you iterate through your array(s) of UIImageViews in a loop, you'll have the same amount of code whether your grid is 4x9 or 40x90. Here is a nice blog post on random number generators: http://ianbullard.squarespace.com/journal/2009/4/28/why-you-should-never-use-rand.html
cduhn
A: 

I would do it programmatically for your sake.

NSArray *myViews = //I assume you can create an array of views

for (int i=0; i<rows; ++i) {
    for (int j=0; j<columns; ++j) {
        UIImageView *thisImageView = [myViews objectAtIndex:(i*columns+j)];
        CGSize size = thisImageView.image.size;
        [thisImageView setFrame:CGRectMake(j*size.width, i*size.height, size.width, size.height)];
        [self.view addSubview:thisImageView];
    }
}

//Later to pick one randomly
UIImageView *myRandomView = [myViews objectAtIndex:(arc4random()%[myViews count])];
[myRandomView setImage:myNewImage];
David Kanarek
A: 

IImageView *myRandomView = [myViews objectAtIndex:(arc4random()%[myViews count])]; [myRandomView setImage:myNewImage];

What is this "myNewimage"? Which will be that image?

Harsh