iOS自定义转场动画

作者: petry | 来源:发表于2016-09-18 11:49 被阅读223次

    通过这几天的学习,我尝试实现了四个效果,废话不多说,先上效果图:

    DEMO ONE:一个神奇移动效果push动画,支持手势pop

    神奇效果.gif

    DEMO TWO:一个弹性的present动画,支持手势present和dismiss

    弹性present.gif

    DEMO THREE:一个翻页push效果,支持手势PUSH和POP

    翻页效果.gif

    DEMO FOUR:一个小圆点扩散present效果,支持手势dimiss

    小圆点扩散.gif

    准备

    从iOS7开始,苹果提供了自定义转场的API,模态推送present和dismiss,导航控制器的push和pop,标签控制器的控制器切换都可以自定义转场了.
    1.我们需要自定义一个遵循的<UIViewControllerAnimatedTransitioning>协议的动画过渡管理对象,并实现两个必须实现的方法:

     // 返回动画事件
    - (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext; 
    // 所有的过渡动画事务都在这个方法里面完成 
    - (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext;
    

    2.我们还需要自定义一个继承于UIPercentDrivenInteractiveTransition的手势过渡管理对象,我把它成为百分比手势过渡管理对象,因为动画的过程是通过百分比控制的
    3.成为相应的代理,实现相应的代理方法,返回我们前两步自定义的对象就OK了 !
    模态推送需要实现如下4个代理方法,iOS8新的那个方法我暂时还没有发现它的用处,所以暂不讨论.

    //返回一个管理present动画过渡的对象
    - (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source;
    //返回一个管理dismiss动画过渡的对象
    - (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed;
    //返回一个管理present手势过渡的对象
    - (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id <UIViewControllerAnimatedTransitioning>)animator;
    //返回一个管理dismiss动画过渡的对象
    - (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id <UIViewControllerAnimatedTransitioning>)animator;
    

    导航控制器实现如下2个代理方法

    //返回转场动画过渡管理对象
    - (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
                              interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController NS_AVAILABLE_IOS(7_0);
    //返回手势过渡管理对象
    - (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                       animationControllerForOperation:(UINavigationControllerOperation)operation
                                                    fromViewController:(UIViewController *)fromVC
                                                      toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0);
    

    标签控制器也有相应的两个方法

    //返回转场动画过渡管理对象
     - (nullable id <UIViewControllerInteractiveTransitioning>)tabBarController:(UITabBarController *)tabBarController
                   interactionControllerForAnimationController: (id <UIViewControllerAnimatedTransitioning>)animationController NS_AVAILABLE_IOS(7_0);
     //返回手势过渡管理对象
     - (nullable id <UIViewControllerAnimatedTransitioning>)tabBarController:(UITabBarController *)tabBarController
         animationControllerForTransitionFromViewController:(UIViewController *)fromVC
                                           toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0);
    

    4.如果看着这些常常的代理方法名头疼的话,没关系,先在demo中用起来吧,慢慢就习惯了,其实哪种自定义转场都只需要这3个步骤,如果不需要手势控制,步骤2还可以取消,现在就让我们动手来实现效果吧

    Let's go!

    DEMO ONE:神奇移动效果

    1.我们首先创建2个控制器,为了方便我称做present操作的为vc1、被present的为vc2,点击一个控制器上的按钮可以push出另一个控制器.
    2.创建一个手势过渡管理的类,我这里是PEInteractiveTransition,因为无论哪一种转场,手势控制的实质都是一样的,我干脆就把这个手势过渡管理的类封装了一下,具体可以在.h文件里面查看,在接下来的三个转场效果中我们都可以便捷的是使用它:
    PEInteractiveTransition.h

    typedef void(^GestureConfig)();
    
    //手势转场类型
    typedef NS_ENUM(NSUInteger,PEInteractiveTransitionType){
        PEInteractiveTransitionTypePresent = 0,
        PEInteractiveTransitionTypeDismiss,
        PEInteractiveTransitionTypePush,
        PEInteractiveTransitionTypePop
    };
    
    //手势方向
    typedef NS_ENUM(NSUInteger,PEInteractiveTransitionGestureDirection){
        PEInteractiveTransitionGestureDirectionLeft = 0,
        PEInteractiveTransitionGestureDirectionRight,
        PEInteractiveTransitionGestureDirectionUp,
        PEInteractiveTransitionGestureDirectionDown
    };
    
    @interface PEInteractiveTransition : UIPercentDrivenInteractiveTransition
    /** 记录是否开始手势,判断pop操作是手势出发还是返回键出发 */
    @property (nonatomic, assign)BOOL interation;
    /** 触发手势present的时候config,在config中初始化并present需要弹出的控制器 */
    @property (nonatomic, copy)GestureConfig presentConfig;
    /** 触发手势push的时候config,在config中初始化并push需要弹出的控制器 */
    @property (nonatomic, copy)GestureConfig pushConfig;
    
    #pragma mark - ---初始化方法---
    + (instancetype)interactiveTransitionWithTransitionType:(PEInteractiveTransitionType)type GestureDirection:(PEInteractiveTransitionGestureDirection)direction;
    - (instancetype)initWithTransitionType:(PEInteractiveTransitionType)type GestureDirection:(PEInteractiveTransitionGestureDirection)direction;
    
    /** 给传入控制器添加手势*/
    - (void)addPanGestureForViewController:(UIViewController *)viewController; 
    @end
    

    PEInteractiveTransition.m

    #import "PEInteractiveTransition.h"
    
    @interface PEInteractiveTransition()
    
    /** 传入的ViewController */
    @property (nonatomic, weak)UIViewController *vc;
    /** 手势方向 */
    @property (nonatomic, assign)PEInteractiveTransitionGestureDirection direction;
    /** 手势类型 */
    @property (nonatomic, assign)PEInteractiveTransitionType type;
    
    @end
    @implementation PEInteractiveTransition
    
    + (instancetype)interactiveTransitionWithTransitionType:(PEInteractiveTransitionType)type GestureDirection:(PEInteractiveTransitionGestureDirection)direction
    {
        return [[self alloc] initWithTransitionType:type GestureDirection:direction];
    }
    
    - (instancetype)initWithTransitionType:(PEInteractiveTransitionType)type GestureDirection:(PEInteractiveTransitionGestureDirection)direction{
        self = [super init];
        if (self) {
            _direction = direction;
            _type = type;
        }
        return self;
    }
    
    - (void)addPanGestureForViewController:(UIViewController *)viewController
    {
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
        self.vc = viewController;
        [viewController.view addGestureRecognizer:pan];
    }
    /**
     *  手势过渡过程
     *
     *  @param pan 添加的手势
     */
    - (void)handleGesture:(UIPanGestureRecognizer *)pan
    {
        //手势百分比 初始化为0  向上和向右滑动 距离是负的 所以前面加负号 这样负负得正
        CGFloat persent = 0;
        switch (_direction) {
            case PEInteractiveTransitionGestureDirectionUp:{
                CGFloat transitionY = -[pan translationInView:pan.view].y;
                persent = transitionY / pan.view.frame.size.width;
            }
                break;
            case PEInteractiveTransitionGestureDirectionRight:{
                CGFloat transitionR = [pan translationInView:pan.view].x;
                persent = transitionR / pan.view.frame.size.width;
            }
                break;
            case PEInteractiveTransitionGestureDirectionDown:{
                CGFloat transitionD = [pan translationInView:pan.view].y;
                persent = transitionD / pan.view.frame.size.width;
            }
                break;
            case PEInteractiveTransitionGestureDirectionLeft:{
                CGFloat transitionL = -[pan translationInView:pan.view].x;
                persent = transitionL / pan.view.frame.size.width;
            }
                break;
                
            default:
                break;
        }
        switch (pan.state) {
            case UIGestureRecognizerStateBegan:{
                //手势开始的时候标记手势状态,并开始相应的事件
                self.interation = YES;
                [self startGesture];
            }
                break;
            case UIGestureRecognizerStateChanged:{
                //手势过程中,通过updateInteractiveTransition设置pop过程进行的百分比
                [self updateInteractiveTransition:persent];
            }
                break;
            case UIGestureRecognizerStateEnded:{
                //手势完成后结束标记并且判断移动的距离是否过半,过则finishInteractiveTransition完成转场操作,否则取消转场操作
                self.interation = NO;
                if (persent > 0.5) {
                    [self finishInteractiveTransition];
                }else {
                    [self cancelInteractiveTransition];
                }
            }
                break;
                
            default:
                break;
        }
    }
    
    - (void)startGesture
    {
        switch (_type) {
            case PEInteractiveTransitionTypePresent:{
                if (_presentConfig) {
                    _presentConfig();
                }
            }
                break;
            case PEInteractiveTransitionTypeDismiss:{
                [_vc dismissViewControllerAnimated:YES completion:nil];
            }
                break;
            case PEInteractiveTransitionTypePush:{
                if (_pushConfig) {
                    _pushConfig();
                }
            }
                break;
            case PEInteractiveTransitionTypePop:{
                [_vc.navigationController popViewControllerAnimated:YES];
            }
                break;
                
            default:
                break;
        }
    }
    
    @end
    

    3.创建神奇效果的具体动画代理
    PENaviTransition.h

    typedef NS_ENUM(NSUInteger, PENaviTransitionType){
        PENaviTransitionTypePush = 0,
        PENaviTransitionTypePop
    };
    
    @interface PENaviTransition : NSObject<UIViewControllerAnimatedTransitioning>
    
    
    + (instancetype)transitionWithType:(PENaviTransitionType)type;
    - (instancetype)initWithTransitionType:(PENaviTransitionType)type;
    
    @end
    

    PENaviTransition.m主要实现一个动画时长方法和一个push动画和一个pop动画

    /**
     *  动画时长
     */
    - (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        return 0.75;
    }
    /**
     *  如何执行过渡动画
     */
    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        switch (_type) {
            case PENaviTransitionTypePush:
                [self doPushAnimation:transitionContext];
                break;
            case PENaviTransitionTypePop:
                [self doPopAnimation:transitionContext];
                break;
                
            default:
                break;
        }
    }
    
    /**
     *  执行push过渡动画
     */
    - (void)doPushAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        PEMagicMoveController *fromVC = (PEMagicMoveController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        PEMagicMovePushController *toVC = (PEMagicMovePushController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        //拿到当前点击的cell的imageView
        PEMagicMoveCell *cell = (PEMagicMoveCell *)[fromVC.collectionView cellForItemAtIndexPath:fromVC.clickIndex];
        UIView *containerView = [transitionContext containerView];
        UIView *tempView = [cell.imageV snapshotViewAfterScreenUpdates:NO];
        //将点击的cell截图作为临时View的内容 并将坐标系转化成push控制器种的坐标
        tempView.frame = [cell.imageV convertRect:cell.imageV.bounds toView:containerView];
        //设置动画前的各个控件的状态
        cell.imageV.hidden = YES;
        toVC.view.alpha = 0;
        toVC.imageView.hidden = YES;
        //tempView添加到containerView中保证在最前方,所以后添加
        [containerView addSubview:toVC.view];
        [containerView addSubview:tempView];
        //开始push动画
        [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 usingSpringWithDamping:0.55 initialSpringVelocity:1/0.55 options:0 animations:^{
            //临时View(也就是截取cell大小)的frame变成和push出来view种的imageView大小一样
            tempView.frame = [toVC.imageView convertRect:toVC.imageView.bounds toView:containerView];
            //push控制器由透明为0变为1
            toVC.view.alpha = 1;
        } completion:^(BOOL finished) {
            tempView.hidden = YES;
            toVC.imageView.hidden = NO;
            //如果动画过渡取消了就标记不完成,否则标记完成,这里可以直接写YES,如果有手势过渡才需要判断,必须标记,否则系统不会完成动画,会出现无法交互等bug
            [transitionContext completeTransition:YES];
        }];
    }
    /**
     *  执行pop过渡动画
     */
    - (void)doPopAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        PEMagicMovePushController *fromVC = (PEMagicMovePushController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        PEMagicMoveController *toVC = (PEMagicMoveController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        PEMagicMoveCell *cell = (PEMagicMoveCell *)[toVC.collectionView cellForItemAtIndexPath:toVC.clickIndex];
        UIView *containerView = [transitionContext containerView];
        //这里的lastObject就是push适合初始化的那个tempView
        UIView *tempView = containerView.subviews.lastObject;
        //设置动画前状态
        cell.imageV.hidden = YES;       //列表页面的cell先隐藏
        fromVC.imageView.hidden = YES;  //当前页面的imageView也进行隐藏
        tempView.hidden = NO;           //最上面的临时View显示
        [containerView insertSubview:toVC.view atIndex:0];
        //开始pop动画
        [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 usingSpringWithDamping:.55 initialSpringVelocity:1/0.55 options:0 animations:^{
            //将临时View的坐标和大小变成新坐标系中列表cell的坐标和大小
            tempView.frame = [cell.imageV convertRect:cell.imageV.bounds toView:containerView];
            //同时详情页面隐藏
            fromVC.view.alpha = 0;
        } completion:^(BOOL finished) {
            //加入了手势判断
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
            if ([transitionContext transitionWasCancelled]) {
                //手势取消了,原来隐藏的imageView要显示出来
                tempView.hidden = YES;
                fromVC.imageView.hidden = NO;
            }else{
                //手势成功
                cell.imageV.hidden = NO;        //列表点击的cell要显示
                [tempView removeFromSuperview]; //临时的要去除 因为下一次会重新生成 不会产生冗余
            }
        }];
    }
    

    4.现在可以在具体进行跳转的页面vc1进行使用

    #pragma mark <UICollectionViewDelegate>
    - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
    {
        //记录点击的是列表的第几个 这样在返回动画的时候能用上
        _clickIndex = indexPath;
        PEMagicMovePushController *vc = [[PEMagicMovePushController alloc] init];
        //设置导航控制器的代理为推出的控制器,可以达到自定义不同控制器推出效果的目的
        self.navigationController.delegate = vc;
        [self.navigationController pushViewController:vc animated:YES];
    }
    

    5.在push出的页面vc2进行过渡动画的监听和实现

    //返回手势过渡管理对象
    - (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC
    {
        //分pop和push两种情况分别返回动画过渡代理相应不同的动画操作
        return [PENaviTransition transitionWithType:operation == UINavigationControllerOperationPush ? PENaviTransitionTypePush : PENaviTransitionTypePop];
    }
    
    //返回转场动画过渡管理对象
    - (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animationController
    {
        //如果是手动出发则返回我们的UIPercentDrivenInteractiveTransition对象
        return _interactiveTransition.interation ? _interactiveTransition : nil;
    }
    

    6.完成,就是下面的效果

    神奇效果.gif

    DEMO TWO: 弹性present动画

    1.创建两个控制器,手势管理类和DEMO ONE是同一个
    2.自己具体的动画过渡实现presentAnimationdismissAnimation两个方法

    /**
     *  presentAnimation
     */
    - (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContent
    {
        UIViewController *toVC = [transitionContent viewControllerForKey:UITransitionContextToViewControllerKey];
        UIViewController *fromVC = [transitionContent viewControllerForKey:UITransitionContextFromViewControllerKey];
        //snapshotViewAfterScreenUpdates:可以对某个试图截图,我们采用对这个截图做动画代替直接对toVC做动画,因为在手势过渡中直接使用toVC动画会和手势有冲突,如果不需要实现手势的话,就可以不是用截图了
        UIView *tempView = [fromVC.view snapshotViewAfterScreenUpdates:NO];
        tempView.frame = fromVC.view.frame;
        //因为对截图做动画,fromVC开始是隐藏的
        fromVC.view.hidden = YES;
        //containerView:如果要对视图做转场动画,视图就必须加入containerView中才能进行,可以理解为containerView管理所有做转场动画的视图
        UIView *containerView = [transitionContent containerView];
        //将截图视图和toVC的view都加入containerView中 截图视图是fromVC所以先放 先放的在下面
        [containerView addSubview:tempView];
        [containerView addSubview:toVC.view];
        //设置toVC的frame,因为是present出来不是全屏,而且在底部,如果不设置默认是整个屏幕,这里的containerView的frame就是整个屏幕
        toVC.view.frame = CGRectMake(0, containerView.height, containerView.width, 500);
        //开始动画,使用产生弹簧效果的方法
        [UIView animateWithDuration:[self transitionDuration:transitionContent] delay:0.0 usingSpringWithDamping:0.55 initialSpringVelocity:1.0 / 0.55 options:0 animations:^{
            //1.让toVC向上移动 向上是负的
            toVC.view.transform = CGAffineTransformMakeTranslation(0, -500);
            //2.让截图视图缩小即可
            tempView.transform = CGAffineTransformMakeScale(0.85, 0.85);
            
        } completion:^(BOOL finished) {
            //使用如下代码标记整个转场过程是否正常完成[transitionContext transitionWasCancelled]代表手势是否取消了,如果取消了就传NO表示转场失败,反之亦然,如果不是用手势的话直接传YES也是可以的,我们必须标记转场的状态,系统才知道处理转场后的操作,否者认为你一直还在,会出现无法交互的情况
            [transitionContent completeTransition:![transitionContent transitionWasCancelled]];
            //转场失败后的处理
            if ([transitionContent transitionWasCancelled])
            {
                //失败后复原动画开始是的样子
                //1.把fromVC显示出来
                fromVC.view.hidden = NO;
                //2.移除截图视图,下次会重新生成
                [tempView removeFromSuperview];
            }
        }];
    }
    
    /**
     *  dismissAnimation
     */
    - (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContent
    {
        UIViewController *fromVC = [transitionContent viewControllerForKey:UITransitionContextFromViewControllerKey];
        UIViewController *toVC = [transitionContent viewControllerForKey:UITransitionContextToViewControllerKey];
        
        //参照present动画的逻辑,present成功后,containerView的第一个子视图就是截图视图,我们将其取出做动画
        UIView *containerView = [transitionContent containerView];
        UIView *tempView = containerView.subviews[0];
        //开始动画
        [UIView animateWithDuration:[self transitionDuration:transitionContent] delay:0.0 usingSpringWithDamping:0.55 initialSpringVelocity:1 / 0.55 options:0 animations:^{
            //present使用的是transform,只需要恢复就可以了
            fromVC.view.transform = CGAffineTransformIdentity;
            tempView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            if ([transitionContent transitionWasCancelled]) {
                //标记失败
                [transitionContent completeTransition:NO];
            }else{
                //成功后,标记成功,让toVC显示出来,并移除截图视图
                [transitionContent completeTransition:YES];
                toVC.view.hidden = NO;
                [tempView removeFromSuperview];
            }
        }];
    }
    

    3.vc1中进行调用

        PEElasticOneController *elasticVC = [PEElasticOneController new];
        elasticVC.delegate = self;
        [self presentViewController:elasticVC animated:YES completion:nil];
    

    4.vc2中监听

    #pragma mark - ---UIViewControllerTransitioningDelegate---
    - (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
    {
        return [PEElasticTransition transitionWithTransitionType:PEElasticTransitionTypePresent];
    }
    - (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
    {
        return [PEElasticTransition transitionWithTransitionType:PEElasticTransitionTypeDismiss];
    }
    - (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id<UIViewControllerAnimatedTransitioning>)animator
    {
        PEInteractiveTransition *interactivePresent = [self.delegate interactiveTransitionForPresent];
        return interactivePresent.interation ? interactivePresent : nil;
    }
    - (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id<UIViewControllerAnimatedTransitioning>)animator
    {
        return self.interactiveTransition.interation ? self.interactiveTransition : nil;
    }
    

    这样就基本完成了

    弹性present.gif

    DEMO THREE:翻页push效果

    1.其它和上面的相似,直接来看核心的过渡动画实现:

    /**
     *  自定义push动画
     */
    - (void)doPushAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        //对当前view截图 然后作为动画对象
        UIView *tempV = [fromVC.view snapshotViewAfterScreenUpdates:NO];
        tempV.frame = fromVC.view.frame;
        UIView *containerV = [transitionContext containerView];
        //临时的放最上面 做过渡
        [containerV addSubview:toVC.view];
        [containerV addSubview:tempV];
        fromVC.view.hidden = YES;
        //设置anchorPoint 选择的支点
        [tempV setAnchorPoint:CGPointMake(0, 0.5)];
        CATransform3D transform3d = CATransform3DIdentity;
        //m34(透视效果,要操作的这个对象要有旋转的角度,否则没有效果。正直/负值都有意义);
        transform3d.m34 = -0.002;
        containerV.layer.sublayerTransform = transform3d;
        //增加阴影
        CAGradientLayer *fromGradient = [CAGradientLayer layer];
        fromGradient.frame = fromVC.view.bounds;
        fromGradient.colors = @[(id)[UIColor blackColor].CGColor,(id)[UIColor blackColor].CGColor];
        fromGradient.startPoint = CGPointMake(0.0, 0.5);
        fromGradient.endPoint = CGPointMake(0.8, 0.5);
        UIView *fromShadow = [[UIView alloc] initWithFrame:fromVC.view.bounds];
        fromShadow.backgroundColor = [UIColor clearColor];
        [fromShadow.layer insertSublayer:fromGradient atIndex:1];
        fromShadow.alpha = 0.0;
        [tempV addSubview:fromShadow];
        CAGradientLayer *toGradient = [CAGradientLayer layer];
        toGradient.frame = fromVC.view.bounds;
        toGradient.colors = @[(id)[UIColor blackColor].CGColor,(id)[UIColor blackColor].CGColor];
        toGradient.startPoint = CGPointMake(0.0, 0.5);
        toGradient.endPoint = CGPointMake(0.8, 0.5);
        UIView *toShadow = [[UIView alloc] initWithFrame:fromVC.view.bounds];
        toShadow.backgroundColor = [UIColor clearColor];
        [toShadow.layer insertSublayer:toGradient atIndex:1];
        toShadow.alpha = 1.0;
        [toVC.view addSubview:toShadow];
        //开始动画
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            //沿Y轴旋转 逆时针180°
            tempV.layer.transform = CATransform3DMakeRotation(-M_PI_2, 0, 1, 0);
            //当前的由亮变暗 push的VC由暗变亮
            fromShadow.alpha = 1.0;
            toShadow.alpha = 0.0;
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
            //动画取消的操作
            if ([transitionContext transitionWasCancelled]){
                [tempV removeFromSuperview];
                fromVC.view.hidden = NO;
            }
        }];
    }
    
    /**
     *  自定义pop动画
     */
    - (void)doPopAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        UIView *containerV = [transitionContext containerView];
        UIView *tempV = containerV.subviews.lastObject;
        [containerV addSubview:toVC.view];
        //开始动画
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            //临时图层恢复原状
            tempV.layer.transform = CATransform3DIdentity;
            fromVC.view.subviews.lastObject.alpha = 1.0;
            tempV.subviews.lastObject.alpha = 0.0;
        } completion:^(BOOL finished) {
            if ([transitionContext transitionWasCancelled]){
                [transitionContext completeTransition:NO];
            }else{
                [transitionContext completeTransition:YES];
                [tempV removeFromSuperview];
                toVC.view.hidden = NO;
            }
        }];
    }
    

    2.手势加上的效果如下:

    ![Uploading 翻页效果_161246.gif . . .]

    DEMO FOUR:圆点扩散present效果

    1.其它和上面相似,来看核心过渡的动画实现

    - (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        UINavigationController *fromVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        UIView *containerV = [transitionContext containerView];
        PECircleSpreadController *temp = fromVC.viewControllers.lastObject;
        [containerV addSubview:toVC.view];
        //画两个圆路径
        UIBezierPath *startCircle = [UIBezierPath bezierPathWithOvalInRect:temp.buttonFrame];
        //始终用最大的x值和y值的平方根 来作为圆的半径 这样保证了圆点中心到最远的边的距离作为半径
        CGFloat x = MAX(temp.buttonFrame.origin.x, containerV.frame.size.width - temp.buttonFrame.origin.x);
        CGFloat y = MAX(temp.buttonFrame.origin.y, containerV.frame.size.height - temp.buttonFrame.origin.y);
        CGFloat radius = sqrtf(pow(x, 2) + pow(y, 2));
        //圆心 半径 开始角度 结束角度M_PI*2是360° 是否顺时针
        UIBezierPath *endCircle = [UIBezierPath bezierPathWithArcCenter:containerV.center radius:radius startAngle:0 endAngle:M_PI * 2 clockwise:YES];
        
        //创建CAShapLayer进行遮盖
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.path = endCircle.CGPath;
        //将maskLayer作为toVC的遮盖
        toVC.view.layer.mask = maskLayer;
        //创建路径动画
        CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
        //动画是添加到layer上的,所以必须为CGPath,再将CGPath桥接为OC对象
        maskLayerAnimation.fromValue = (__bridge id)(startCircle.CGPath);
        maskLayerAnimation.toValue = (__bridge id)(endCircle.CGPath);
        maskLayerAnimation.duration = [self transitionDuration:transitionContext];
        maskLayerAnimation.delegate = self;
        maskLayerAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];   //动画速度: 先慢 后慢 中间快
        [maskLayerAnimation setValue:transitionContext forKey:@"transitionContext"];
        [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];    
    }
    
    - (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        PECircleSpreadPresentedController *fromVC = (PECircleSpreadPresentedController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        UINavigationController *toVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        PECircleSpreadController *temp = toVC.viewControllers.lastObject;
        UIView *containerV = [transitionContext containerView];
        //画两个圆的路径
        CGFloat radius = sqrtf(pow(containerV.frame.size.height, 2) + pow(containerV.frame.size.width, 2))/2.0;
        UIBezierPath *startCircle = [UIBezierPath bezierPathWithArcCenter:containerV.center radius:radius startAngle:0 endAngle:M_PI*2 clockwise:YES];
        temp.buttonFrame = fromVC.presentButtonFrame;
        UIBezierPath *endCircle = [UIBezierPath bezierPathWithOvalInRect:temp.buttonFrame];
        //创建CAShapeLayer进行覆盖
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.fillColor = [UIColor greenColor].CGColor;
        maskLayer.path = endCircle.CGPath;
        fromVC.view.layer.mask = maskLayer;
        //创建路径动画
        CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
        maskLayerAnimation.delegate = self;
        maskLayerAnimation.fromValue = (__bridge id)(startCircle.CGPath);
        maskLayerAnimation.toValue = (__bridge id)(endCircle.CGPath);
        maskLayerAnimation.duration = [self transitionDuration:transitionContext];
        maskLayerAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [maskLayerAnimation setValue:transitionContext forKey:@"transitionContext"];
        [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];
        
    }
    
    - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
    { 
        switch (_type) {
            case PECircleSpreadTransitionTypePresent:{
                id<UIViewControllerContextTransitioning> transitionContext = [anim valueForKey:@"transitionContext"];
                [transitionContext completeTransition:YES];
            }
                break;
            case PECircleSpreadTransitionTypeDismiss:{
                id<UIViewControllerContextTransitioning> transitionContext = [anim valueForKey:@"transitionContext"];
                [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
                if ([transitionContext transitionWasCancelled]) {
                    //去掉遮挡层
                    [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view.layer.mask = nil;
                }
            }
                break;
                
            default:
                break;
        }
    }
    

    注意:最后animationDidStop的代理方法中处理到动画的完成逻辑.
    2.最后的效果如下:

    小圆点扩散.gif
    总结
    1、关于:self.modalPresentationStyle = UIModalPresentationCustom;我查看了视图层级后发现,如果使用了Custom,在present动画完成的时候,presentingView也就是demo one中的vc1的view会从containerView中移除,只是移除,并未销毁,此时还被持有着(dismiss后还得回来呢!),如果设置custom,那么present完成后,它一直都在containerView中,只是在最后面,所以需不需要设置custom可以看动画完成后的情况,是否还需要看见presentingViewController,但是记住如果没有设置custom,在disMiss的动画逻辑中,要把它加回containerView中,不然就不在咯~!
    2、感觉写了好多东西,其实只要弄懂了转场的逻辑,其实就只需要写动画的逻辑就行了,其他东西都是固定的,而且苹果提供的这种控制转场的方式可充分解耦,除了写的手势过渡管理可以拿到任何地方使用,所有的动画过渡管理者都可以很轻松的复用到其他转场中,都不用分是何种转场,demo没有写标签控制器的转场,实现方法也是完全类似的,大家可以尝试一下,四个demo的github地址:自定义转场动画demo

    相关文章

      网友评论

        本文标题:iOS自定义转场动画

        本文链接:https://www.haomeiwen.com/subject/piowettx.html