How to prevent CALayer from implicit animations?

2020-02-19 08:09发布

问题:

When I set the backgroundColor property of an CALayer instance, the change seems to be slightly animated. But I don't want that in my case. How can I set the backgroundColor without animation?

回答1:

You can wrap the change in a CATransaction with disabled animations:

[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
//change background colour
[CATransaction commit];


回答2:

[CATransaction begin];
[CATransaction setDisableActions:YES];
//your code here        
[CATransaction commit];


回答3:

Swift

There are a couple other Swift answers here already, but I think this is the most basic answer:

CATransaction.begin()
CATransaction.setDisableActions(true)

// change the layer's background color

CATransaction.commit()


回答4:

Try giving your layer a delegate and then have the delegate implement:

- (id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)key {
    return [NSNull null];
}


回答5:

If you want to disable implicit animations for a property completely, you can do so by assigning to the actions dictionary:

myLayer.actions = @{@"backgroundColor": [NSNull null]};

If you wish to disable the implicit animation on a case by case basis, then using [CATransaction setDisableActions:YES] is still the better way to do it.



回答6:

I've taken Ben's answer and made a Swift helper function, here it is in case it'll be useful for anyone:

func withoutCAAnimations(closure: () -> ()) {
    CATransaction.begin()
    CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
    closure()
    CATransaction.commit()
}

# Example usage:
withoutCAAnimations { layer.backgroundColor = greenColor; }


回答7:

Stop implicit animation on a layer in swift:

override func actionForLayer(layer: CALayer, forKey event: String) -> CAAction? {
    return NSNull()
}

Remember to set the delegate of your CALayer instance to an instance of a class that at least extends NSObject. In this example we extend NSView.