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
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.