How do I bring a CALayer sublayer
to the front of all sublayers, analogous to -[UIView bringSubviewToFront]
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With