21

I 've an infinite animation (rotating an image, type: CABasicAnimation) in my UIView with

animation.repeatCount = HUGE_VALF;

When I push a new ViewController and go back to the initial ViewController with the animation containing View inside, the rotation stopped.

Even if I set up the animation again when the ViewController's viewWillAppear method gets called, it won't rotate again.

What am I doing wrong?

pinki
  • 902
  • 2
  • 12
  • 29

2 Answers2

76

Actually, there is a simple way to solve this
setting your animation to this:

Swift 3 version

animation.removedOnCompletion = false

Swift 4 version

animation.isRemovedOnCompletion = false

The layer itself isn't destroyed, when NavigationController is being pushed to another ViewController's view, because UINavigationController got viewControllers property which will retain the original viewController and therefore its view and your animated layer.

It is this CABasicAnimation object destroyed when view removed from interface even though you set its repeatCount to infinite. So set the isRemovedOnCompletion to false to keep it.

x0 z1
  • 1,704
  • 1
  • 9
  • 12
dispute
  • 1,424
  • 13
  • 17
  • 1
    True. My animation worked fine on iOS8 but iOS9 requires this setting. – SoftDesigner May 06 '16 at 17:28
  • 1
    I have kind of a similar problem. My view that is pulsing is inside of a `UICollectionView` and when I reload my collectionView, the animations stop. Any idea on where to start searching for that? – Georg Apr 04 '17 at 09:24
  • Hmm, this is a great tip, but indeed it does not help in the UITableView case :/ – Fattie May 09 '17 at 19:42
  • Another tip: Setting `isRemovedOnCompletion` to false did not solved the issue for me. In my case I did not push a new VC into the navigation stack, but presented another VC modally. I wrote a custom CALayer subclass that did handle the animation (using code generated by PaintCode). Overriding `removeAllAnimations` in the CALayer subclass + setting the animations `isRemovedOnCompletion` property to false did solve the issue finally. – Baran Feb 11 '19 at 14:23
5

When a layer is removed from the screen, it loses its animations. You need to add them back once the layer is on the screen again.

viewWillAppear: is too early, because the layer isn't actually on the screen by that time. Try adding the animation in viewDidAppear:.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848