Search code examples
uiviewios6core-animation

iOS Restart animation after switching tab


In this post the author said that we could restart animation after switching tab in viewWillAppear.

I called my startAnimation in both viewWillAppear and viewDidAppear, but still failed.

Below is part of my code.

- (void)startAnimation {
    [UIView setAnimationsEnabled:YES];
    [UIView animateWithDuration:0.5f
            delay:0.0f
            options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat
            animations:^(void){
                self.foreground.transform = CGAffineTransformMakeTranslation(0.0f, 5.0f);
            }
            completion:nil];
}

The animation works perfectly when first shown by calling startAnimation in viewDidLoad, but it never works after switching to other tabs.

Neither does it work after the application restarts from the background, even if I've registered an observer of UIApplicationWillEnterForegroundNotification for startAnimation.

Please help me, I'm new to iOS development, thanks very much.


Solution

  • The method viewDidLoad only gets called when your view controller is first loaded.

    If you want your animation to run when you return from other view controllers to this one, you should call the animation method in viewWillAppear, not viewDidLoad.

    To make the animation go back to it's previous value and then animate again, you would first set your view's transform to identity (setting it to the starting point) and then invoke your animationWithDuration method.

    You might find it easier to animate your view's frame.origin or center property rather than changing the transform. Changing the transform gets complicated when you combine translations with rotations, scale changes, etc. Also, the frame property is no longer valid when the transform property is not == the identity transform.