开发者

How to prevent CALayer from implicit animations?

开发者 https://www.devze.com 2023-01-19 16:02 出处:网络
When I set the backgroundColor property of an CALayer instance, the change seems to be slightly animated. But I don\'t want that in m开发者_开发百科y case. How can I set the backgroundColor without an

When I set the backgroundColor property of an CALayer instance, the change seems to be slightly animated. But I don't want that in m开发者_开发百科y case. How can I set the backgroundColor without animation?


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

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


Objective C:

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

Swift:

CATransaction.begin()
CATransaction.setDisableActions(true)

// your code here        
CATransaction.commit()


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()


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

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


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.


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; }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消