iphone: Restart looping animation after view is hi

2019-06-22 03:33发布

问题:

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.

回答1:

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.



回答2:

You can set the animation to continue in the applicationWillEnterForeground method from the AppDelegate. If you have a reference to the first tab's view controller in the AppDelegate, simply call the view controller's viewWillAppear method from the AppDelegate.