简体   繁体   中英

iPhone SDK: repeat subviews

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM