Search code examples
iphoneiosanimationuiviewcore-animation

iphone: Restart looping animation after view is hidden, then reappears?


My app has a tab bar with two different views. On the first tab, its view has a continuously-looping animation.

When I click on the second tab, then go back to the first, the animation has stopped. I know I could start it again in a viewWillAppear: method, but the problem is bigger than that. Specifically, the animation will also stop if the app transitions to the background state, then moves back to the foreground. In that case, viewWillAppear is not called upon the foreground transition, so the viewWillAppear technique wouldn't do anything.

What's the best way to handle this situation?

Thanks.


Solution

  • To maintain encapsulation, you rightly don't want your AppDelegate to know which views need to resume animations. But you can have the view that contains the animation register for corresponding notification (for example in the view's init method) and restart the animation on itself.

    [[NSNotificationCenter defaultCenter] 
       addObserver:self 
          selector:@selector(startAnimation) 
              name:UIApplicationWillEnterForegroundNotification  
            object:nil];
    

    ...and don't forget to deregister from the notification center in the dealloc method.