Thursday 29 September 2016

Custom view controller transition and animation

iOS7 introduced a way by which we can customise the transition from one view controller to other. For example say if we  navigate from one view controller to another  , we push a view controller on another and to return back to initial view controller we pop the view controller.
With iOS7 now we can change the animation according to out requirement. We can reverse the direction of navigation controller. Even we can change the direction of the presenting view controller .
For creating custom transitioning we have to perform following steps:

1) Create a class that implements the UIViewControllerAnimatedTransitioning protocol . In this class we code to customise the animation . In this class we implements the two delegate method of the above protocol , which is as:

-(NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
    return 1.5;

}

-(void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{}

2) In view controller class (a view controller from which we navigate or transition to another  view controller), implements the following:

       If we are presenting a view controller modally, then view controller have to implement UIViewControllerTransitioningDelegate . UIviewController has a property named transitionDelegate set it to self in order to return the custom animation for transitioning .
In delegate method (animationControllerForPresentedController) return the instance of the class which implements the  UIViewControllerAnimatedTransitioning .

      If we are navigating from one view controller to another , the view controller have to implement UINavigationControllerDelegate . The set the view controller as delegate of the navigation controller . And implement the required methods .
For customising the push and pop operation , we can create the two classes one for push animation and another for pop operation which implements the UIViewControllerAnimatedTransitioning . 
And then  from the delegate method of the navigation controller we can check the type of operation (push or pop)and return the  designated custom animator instance .

- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
}

With this way we can create the custom animation as we want. The core part of this process is to code the custom animation . And return the instance of the  custom animation objects.

No comments:

Post a Comment