iOS Core Animation: CALayer bringSublayerToFront?

前端 未结 8 1693
情深已故
情深已故 2020-12-25 12:28

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

8条回答
  •  被撕碎了的回忆
    2020-12-25 13:02

    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.

提交回复
热议问题