Search code examples
keydocumentationcore-animation

Importance of CABasicAnimation key name


I wonder what's the importance of the key when adding CABasicAnimation to a layer. I have several views visible at the same time. To each I apply a function so that it is animated. In summary this function does a lot of things and ends up with:

layer.add(animation, forKey: "jiggle")

As the animation is called on each view, should it have a different key or whatever?

The doc says:

Only one animation per unique key is added to the layer.

But it doesn't say if it should be unique to the entire application.


Solution

  • The key is per layer. The whole idea is you can't have more than one animation with the same key on any given layer. The key allows you to remove the animation from the layer using CALayer removeAnimation(forKey:) or to retrieve the animation with animation(forKey:).

    The full comment on the key parameter of CALayer add(animation:forKey:) states:

    A string that identifies the animation. Only one animation per unique key is added to the layer. The special key kCATransition is automatically used for transition animations. You may specify nil for this parameter.

    Note the mention of kCATransition and nil. If the key wasn't per layer then only one layer in the entire app (or even system) could be nil or use kCATransition.

    Think of it like a dictionary where each layer has its own dictionary. Two different layers have two different dictionaries so there's no worry about key conflicts between the two.