Search code examples
ioscore-animation

Old CALayer animation stays applied


I have a weird problem with CALayer animations. List of actions which lead to this:

  • I add an opacity animation to a CALayer (CAKeyframeAnimation). FillMode being kCAFillModeForwards or kCAFillModeRemoved makes no difference.
  • To resize that layer (after a screen rotation for example) I pause the animation at time X, set the CALayer beginTime and timeOffset to 0 (just to be sure) and call removeAllAnimations() on that layer.
  • I update the frame of the layer.
  • Then I add the new opacity animation.

Problem is: The layer has the correct size and the opacity animations only after time X, before that it's stuck at full opacity and has its old size! Which is really strange, because the size was never animated and I changed the size while no animations were applied to the layer.

Also all superlayers have beginTime == 0 and timeOffset == 0.

Why does that happen?


Solution

  • I found out why this fails. If the layout changes, e.g. with a screen rotation, the OS automatically animates all layers, UIViews, etc. to their new states via "actions". They are added to already existing animations, completely ignoring if the user has already their own animation added. Problem is: This works only with the most simple cases, if you have a little bit more complex animations your animations get broken. To stop the OS from interfering with your animations just assign your CALayer actions property to

    ["bounds": NSNull(),
     "contents": NSNull(),
     "contentsGravity": NSNull(),
     "contentsScale": NSNull(),
     "fontSize": NSNull(),
     "hidden": NSNull(),
     "onLayout": NSNull(),
     "onOrderIn": NSNull(),
     "onOrderOut": NSNull(),
     "position": NSNull(),
     "speed": NSNull(),
     "timeOffset": NSNull()]
    

    Which blocks most actions from being added by the OS (this list may be incomplete).

    If you read tutorials and documentation for Core Animation you won't find any warnings to look out for "actions" animations interfering with your stuff, so it's not an obvious solution, but it works.