views:

447

answers:

1

I have one UIView, which I'm using as my main view, and I want to repeat the subview across the screen. How exactly can I do this?

+1  A: 

You can look at Core Animation. There is a layer called the CAReplicatorLayer that might help you. Alternatively you can use generic CALayers and set their contents all to the same image. You would just need to figure out the width of your parent view and how big you want each tile to be and then just create CALayers for each tile shifting the position of each new layer depending on your grid dimensions. Something like this:

UIImage *imageToReplicate = [UImage imageNamed:@"tile"];
for (i = 0; i < 10; ++i)
{
    for (j=0; j < 10; ++j)
    {
        CGFloat xPos = 0.0; // Calculate your x position
        CGFloat yPos = 0.0; // Calculate your y position

        CALayer *layer = [CALayer layer];
        [layer setBounds:CGRectMake(0.0f, 0.0f, TILE_WIDTH, TILE_HEIGHT)];
        [layer setPosition:CGPointMake(xPos, yPos)];
        [layer setContents:(id)[image CGImage]];
        [[[self view] layer] addSublayer:layer];
    }
}

You'll have to figure out the calculation for each iteration of your layer positions. Remember that by default the anchor point of the layer is its center. You either calculate it by subtracting half of the layer tile size or you can change the anchor point to be a corner instead. For more information on that, take a look at the layer geometry section of the Core Animation documentation.

Matt Long
will it work with a UIview?
Matt S.
Yes. In the example code I provided the line [[[self view] layer] addSublayer:layer];, the view there is a UIView. UIView's have a layer tree represented by the field -sublayers. You are adding sublayers to the UIView's layer tree.
Matt Long