ViewController之间的切换动画

一 、API介绍

iOS7开始,苹果推出了自定义转场动画API。从此,任何可以用Core Animation实现的动画,都可以出现在两个ViewController的切换之间

知识点图:

ViewController之间的切换动画_第1张图片 

从上图可以看出,新的Api主要提供了2中VC切换方式,动画式切换,交互式切换。

二 、动画式切换,实现方法:

1,创建继承自NSObject并且声明 UIViewControllerAnimatedTransitioning的动画类;

#import <UIKit/UIKit.h>
@interface PagingTransition : NSObject<UIViewControllerAnimatedTransitioning>

@end

2,重载 UIViewControllerAnimatedTransitioning 中的协议方法。 

#import "PagingTransition.h"

@implementation PagingTransition

//返回动画的时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    
    return  1;
    
}
//在进行切换的时候将调用该方法,我们对于切换时的UIView的设置和动画都在这个方法中完成。
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    
    UIViewController* toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController* fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    [[transitionContext containerView] addSubview:toVC.view];
    
    /**
     *  效果1
     */
    
    toVC.view.alpha = 0;
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromVC.view.transform = CGAffineTransformMakeScale(0.1, 0.1);
        toVC.view.alpha = 1;
    } completion:^(BOOL finished) {
        fromVC.view.transform = CGAffineTransformIdentity;
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        
    }];
    
    /**
     *  另一种效果
     */
//    CGRect  finalRect = [transitionContext finalFrameForViewController:toVC];
//    
//    toVC.view.frame = CGRectOffset(finalRect, 0, [[UIScreen mainScreen]bounds].size.height);
//    
//    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 usingSpringWithDamping:0.8 initialSpringVelocity:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
//        toVC.view.frame = finalRect;
//    } completion:^(BOOL finished) {
//        //5
//        [transitionContext completeTransition:YES];
//    }];
//    
}

@end

 

3, 在ViewController中实现 UINavigationControllerDelegate 方法,并指定delegate。

self.navigationController.delegate = self;
#pragma mark--  UINavigationControllerDelegate
- (id<UIViewControllerAnimatedTransitioning>) navigationController:(UINavigationController *)navigationController
     animationControllerForOperation:(UINavigationControllerOperation)operation   fromViewController:(UIViewController*)fromVC
     toViewController:(UIViewController*)toVC
{
    if (operation == UINavigationControllerOperationPush) {
        PagingTransition *ping = [PagingTransition new];
        return ping;
    }
    return nil;
}

 

三、交互式切换 ,会根据交互式手势来切换VC并同时播放动画效果。 

参考: http://www.cocoachina.com/industry/20140623/8918.html

例子:https://github.com/PeteC/InteractiveViewControllerTransitions

 

你可能感兴趣的:(ViewController之间的切换动画)