iOS Core Animation: CALayer bringSublayerToFront? iOS Core Animation: CALayer bringSublayerToFront? objective-c objective-c

iOS Core Animation: CALayer bringSublayerToFront?


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.


Right code here

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