How do I bring a CALayer sublayer
to the front of all sublayers, analogous to -[UIView bringSubviewToFront]
?
You can implement this functionality in a category on CALayer like so:
CALayer+Extension.h
#import <QuartzCore/QuartzCore.h>
typedef void (^ActionsBlock)(void);
@interface CALayer (Extension)
+ (void)performWithoutAnimation:(ActionsBlock)actionsWithoutAnimation;
- (void)bringSublayerToFront:(CALayer *)layer;
@end
CALayer+Extension.m
#import "CALayer+Extension.h"
@implementation CALayer (Extension)
+ (void)performWithoutAnimation:(ActionsBlock)actionsWithoutAnimation
{
if (actionsWithoutAnimation)
{
// Wrap actions in a transaction block to avoid implicit animations.
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
actionsWithoutAnimation();
[CATransaction commit];
}
}
- (void)bringSublayerToFront:(CALayer *)layer
{
// Bring to front only if already in this layer's hierarchy.
if ([layer superlayer] == self)
{
[CALayer performWithoutAnimation:^{
// Add 'layer' to the end of the receiver's sublayers array.
// If 'layer' already has a superlayer, it will be removed before being added.
[self addSublayer:layer];
}];
}
}
@end
And for easy access you can #import "CALayer+Extension.h"
in your project's Prefix.pch (precompiled header) file.
Create a category of CALayer like this:
@interface CALayer (Utils)
- (void)bringSublayerToFront;
@end
@implementation CALayer (Utils)
- (void)bringSublayerToFront {
CGFloat maxZPosition = 0; // The higher the value, the closer it is to the front. By default is 0.
for (CALayer *layer in self.superlayer.sublayers) {
maxZPosition = (layer.zPosition > maxZPosition) ? layer.zPosition : maxZPosition;
}
self.zPosition = maxZPosition + 1;
}
@end