How can I tile the background with UIImageViews with code efficiently?

306 Views Asked by At

I'm working in Xcode 6 on tiling the iPhone background with many UIImageViews and I'd like to know if this is the most efficient solution.

I know one simple solution would be to create image views in the storyboard and cover the entire screen with them manually. I'd like to do it with code. Here's the code I have currently (5x5 is an okay size since I can scale it up or down to fill the screen with bigger or larger images):

CGRect tiles[5][5];
UIImage *tileImages[5][5];
UIImageView *tileViews[5][5];

for(int i=0;i<5;i++)
{
    for(int j=0;j<5;j++)
    {
        tiles[i][j] = CGRectMake(50*i,50*j,50,50);
        tileImages[i][j] = [UIImage imageNamed:@"tile.png"];
        tileViews[i][j] = [[UIImageView alloc] initWithFrame:tiles[i][j]];
        tileViews[i][j].image = tileImages[i][j];
        [self.view addSubview:tileViews[i][j]];
    }
}

Currently all the images are the same, but in the long haul I'm going to make them dependent on various factors.

I have read around and I know that UIImageViews are finicky. Is this the proper and memory efficient way to tile a background with UIImageViews? Is there a better way to do this? Can I manually go in after the tiles are initialized and change an image it's displaying and have it update in real time with just this?

tileView[1][2].image = [UIImage imageNamed:@"anotherTile.png"];

Thanks in advance, I just finished a basic 6-week course in IOS programming at my college so I still find myself trying to appease the Objective C Gods occasionally.

1

There are 1 best solutions below

3
On BEST ANSWER

I guess my doubt would be why you need them to be image views. Drawing an image in a view or layer is so easy, and arranging views or layers in a grid is so easy; what are the image views for, when you are not really using or needing any of the power of image views?

I have several apps that display tiled images - one shows 99 bottles in a grid, one shows a grid of tile "pieces" that the user taps in matched pairs to dismiss them, one shows a grid of rectangular puzzle pieces that the user slides to swap them and get them into the right order, and one shows a grid of "cards" that the user taps in triplets to match them - and in none of those cases do I use image views. In one, they are CALayers; in the other cases they are custom UIView subclasses; but in no case do I use UIImageViews.

For something as simple as a grid of images, using UIImageViews seems, as you seem to imply, overkill. If the reason you have resorted to UIImageViews is that you don't know how to make a UIView or a CALayer draw its content, I'd say, stop and learn how to do that before you go any further.