How to prevent CALayer from implicit animations?

2020-02-19 07:46发布

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?

7条回答
The star\"
2楼-- · 2020-02-19 08:14

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()
查看更多
叛逆
3楼-- · 2020-02-19 08:16

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; }
查看更多
爷的心禁止访问
4楼-- · 2020-02-19 08:27
[CATransaction begin];
[CATransaction setDisableActions:YES];
//your code here        
[CATransaction commit];
查看更多
叛逆
5楼-- · 2020-02-19 08:28

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.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2020-02-19 08:34

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

[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
//change background colour
[CATransaction commit];
查看更多
Viruses.
7楼-- · 2020-02-19 08:37

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.

查看更多
登录 后发表回答