Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Core Animation: CALayer bringSublayerToFront?

How do I bring a CALayer sublayer to the front of all sublayers, analogous to -[UIView bringSubviewToFront]?

like image 421
ma11hew28 Avatar asked Jul 01 '11 11:07

ma11hew28


2 Answers

I'm curious why none of these answers mention the zPosition attribute on CALayer. Core Animation looks at this attribute to figure out layer rendering order. The higher the value, the closer it is to the front. These answers all work as long as your zPosition is 0, but to easily bring a layer to the front, set its zPosition value higher than all other sublayers.

like image 72
Shaun Budhram Avatar answered Nov 10 '22 08:11

Shaun Budhram


This is variation of @MattDiPasquale's implementation which reflects UIView's logic more precisely:

- (void) bringSublayerToFront:(CALayer *)layer
{
    [layer removeFromSuperlayer];
    [self insertSublayer:layer atIndex:[self.sublayers count]];
}

- (void) sendSublayerToBack:(CALayer *)layer
{
    [layer removeFromSuperlayer];
    [self insertSublayer:layer atIndex:0];
}

Note: if you don't use ARC, you may wish to add [layer retain] at top and [layer release] at bottom of both functions to make sure layer is not accidentally destructed in a case it has retain count = 1.

like image 44
ivanzoid Avatar answered Nov 10 '22 09:11

ivanzoid