iOS自定义转场动画

作者: wazrx | 来源:发表于2015-11-27 15:57 被阅读51397次

更新,更简单的自定义转场集成!

几句代码快速集成自定义转场效果+ 全手势驱动

写在前面

这两天闲下来好好的研究了一下自定义转场,关于这方面的文章网络上已经很多了,作为新手,我想通过这篇文章把自己这几天的相关学习心得记录一下,方便加深印响和以后的回顾,这是我第一写技术文章,不好之处请谅解,通过这几天的学习,我尝试实现了四个效果,废话不多说,先上效果图:

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

弹性pop

DEMO TWO:一个类似于KeyNote的神奇移动效果push动画,支持手势pop

神奇移动

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

翻页效果

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

扩散效果

动手前

大家都知道从iOS7开始,苹果就提供了自定义转场的API,模态推送present和dismiss、导航控制器push和pop、标签控制器的控制器切换都可以自定义转场了,关于过多的理论我就不太多说明了,大家可以先参照onevcat大神的这篇博客:WWDC 2013 Session笔记 - iOS7中的ViewController切换,我想把整个自定义转场的步骤做个总结:

  1. 我们需要自定义一个遵循的<UIViewControllerAnimatedTransitioning>协议的动画过渡管理对象,并实现两个必须实现的方法:

     //返回动画事件  
     - (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext;
     //所有的过渡动画事务都在这个方法里面完成
     - (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext;
    
  2. 我们还需要自定义一个继承于UIPercentDrivenInteractiveTransition的手势过渡管理对象,我把它成为百分比手势过渡管理对象,因为动画的过程是通过百分比控制的

  3. 成为相应的代理,实现相应的代理方法,返回我们前两步自定义的对象就OK了 !

    模态推送需要实现如下4个代理方法,iOS8新的那个方法我暂时还没有发现它的用处,所以暂不讨论

     //返回一个管理prenent动画过渡的对象
     - (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source;
     //返回一个管理pop动画过渡的对象
     - (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed;
     //返回一个管理prenent手势过渡的对象
     - (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id <UIViewControllerAnimatedTransitioning>)animator;
     //返回一个管理pop动画过渡的对象
     - (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还可以取消,现在就让我们动手来实现效果吧

动手吧!

demo one

1、我们首先创建2个控制器,为了方便我称做present操作的为vc1、被present的为vc2,点击一个控制器上的按钮可以push出另一个控制器
2、 然后我们创建一个过渡动画管理的类,遵循<UIViewControllerAnimatedTransitioning>协议,我这里是XWPresentOneTransition,由于我们要同时管理present和dismiss2个动画,你可以实现相应的两个类分别管理两个动画,但是我觉得用一个类来管理就好了,看着比较舒服,逻辑也比较紧密,因为present和dismiss的动画逻辑很类似,写在一起,可以相互参考,所以我定义了一个枚举和两个初始化方法:

    XWPresentOneTransition.h

    typedef NS_ENUM(NSUInteger, XWPresentOneTransitionType) {
        XWPresentOneTransitionTypePresent = 0,//管理present动画
        XWPresentOneTransitionTypeDismiss//管理dismiss动画
    };

    @interface XWPresentOneTransition : NSObject<UIViewControllerAnimatedTransitioning>
    //根据定义的枚举初始化的两个方法
    + (instancetype)transitionWithTransitionType:(XWPresentOneTransitionType)type;
    - (instancetype)initWithTransitionType:(XWPresentOneTransitionType)type;   

3、 然后再.m文件里面实现必须实现的两个代理方法

    @implementation XWPresentOneTransition
    - (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
        return 0.5;
    }

    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
        //为了将两种动画的逻辑分开,变得更加清晰,我们分开书写逻辑,
        switch (_type) {
            case XWPresentOneTransitionTypePresent:
                [self presentAnimation:transitionContext];
                break;
        
            case XWPresentOneTransitionTypeDismiss:
                [self dismissAnimation:transitionContext];
                break;
        }
    }
    //实现present动画逻辑代码
    - (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
    }
    //实现dismiss动画逻辑代码
    - (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{

    }  

4、 设置vc2的transitioningDelegate,我就设为它自己咯,我实在vc2的init方法中设置的,并实现代理方法

    - (instancetype)init
    {
        self = [super init];
        if (self) {
            self.transitioningDelegate = self;
            //为什么要设置为Custom,在最后说明.
            self.modalPresentationStyle = UIModalPresentationCustom;
        }
        return self;
    }
    
    - (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
        //这里我们初始化presentType
        return [XWPresentOneTransition transitionWithTransitionType:XWPresentOneTransitionTypePresent];
    }
    - (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
        //这里我们初始化dismissType
        return [XWPresentOneTransition transitionWithTransitionType:XWPresentOneTransitionTypeDismiss];
    }  

5、 至此我们所有的准备工作就做好了,下面只需要专心在presentAnimation:方法和dismissAnimation方法中实现动画逻辑就OK了,先看presentAnimation:

        - (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{`
        //通过viewControllerForKey取出转场前后的两个控制器,这里toVC就是vc1、fromVC就是vc2
        UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        //snapshotViewAfterScreenUpdates可以对某个视图截图,我们采用对这个截图做动画代替直接对vc1做动画,因为在手势过渡中直接使用vc1动画会和手势有冲突, 如果不需要实现手势的话,就可以不是用截图视图了,大家可以自行尝试一下
        UIView *tempView = [fromVC.view snapshotViewAfterScreenUpdates:NO];
        tempView.frame = fromVC.view.frame;
        //因为对截图做动画,vc1就可以隐藏了
        fromVC.view.hidden = YES;
        //这里有个重要的概念containerView,如果要对视图做转场动画,视图就必须要加入containerView中才能进行,可以理解containerView管理着所有做转场动画的视图
        UIView *containerView = [transitionContext containerView];
        //将截图视图和vc2的view都加入ContainerView中
        [containerView addSubview:tempView];
        [containerView addSubview:toVC.view];
        //设置vc2的frame,因为这里vc2present出来不是全屏,且初始的时候在底部,如果不设置frame的话默认就是整个屏幕咯,这里containerView的frame就是整个屏幕
        toVC.view.frame = CGRectMake(0, containerView.height, containerView.width, 400);
        //开始动画吧,使用产生弹簧效果的动画API
        [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:0.55 initialSpringVelocity:1.0 / 0.55 options:0 animations:^{
            //首先我们让vc2向上移动
            toVC.view.transform = CGAffineTransformMakeTranslation(0, -400);
            //然后让截图视图缩小一点即可
            tempView.transform = CGAffineTransformMakeScale(0.85, 0.85);
        } completion:^(BOOL finished) {
            //使用如下代码标记整个转场过程是否正常完成[transitionContext transitionWasCancelled]代表手势是否取消了,如果取消了就传NO表示转场失败,反之亦然,如果不用手势present的话直接传YES也是可以的,但是无论如何我们都必须标记转场的状态,系统才知道处理转场后的操作,否者认为你一直还在转场中,会出现无法交互的情况,切记!
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
            //转场失败后的处理
            if ([transitionContext transitionWasCancelled]) {
                //失败后,我们要把vc1显示出来
                fromVC.view.hidden = NO;
                //然后移除截图视图,因为下次触发present会重新截图
                [tempView removeFromSuperview];
            }
         }];
        } 

再看dismissAnimation 方法

        - (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
        //注意在dismiss的时候fromVC就是vc2了,toVC才是VC1了,注意这个关系
        UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        //参照present动画的逻辑,present成功后,containerView的最后一个子视图就是截图视图,我们将其取出准备动画
        UIView *tempView = [transitionContext containerView].subviews[0];
        //动画吧
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            //因为present的时候都是使用的transform,这里的动画只需要将transform恢复就可以了
            fromVC.view.transform = CGAffineTransformIdentity;
            tempView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            if ([transitionContext transitionWasCancelled]) {
                //失败了标记失败
                [transitionContext completeTransition:NO];
            }else{
                //如果成功了,我们需要标记成功,同时让vc1显示出来,然后移除截图视图,
                [transitionContext completeTransition:YES];
                toVC.view.hidden = NO;
                [tempView removeFromSuperview];
            }
            }];
        } 

6、如果不需要手势控制,这个转场就算完成了,下面我们来添加手势,首先创建一个手势过渡管理的类,我这里是XWInteractiveTransition,因为无论哪一种转场,手势控制的实质都是一样的,我干脆就把这个手势过渡管理的类封装了一下,具体可以在.h文件里面查看,在接下来的三个转场效果中我们都可以便捷的是使用它 .m文件说明

        //通过这个方法给控制器的View添加相应的手势
        - (void)addPanGestureForViewController:(UIViewController *)viewController{
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
        //将传入的控制器保存,因为要利用它触发转场操作
        self.vc = viewController;
        [viewController.view addGestureRecognizer:pan];    
        }  
        
        //关键的手势过渡的过程
        - (void)handleGesture:(UIPanGestureRecognizer *)panGesture{
        //persent是根据panGesture的移动距离获取的,这里就不说明了,可具体去代码中查看
        switch (panGesture.state) {
        case UIGestureRecognizerStateBegan:
            //手势开始的时候标记手势状态,并开始相应的事件,它的作用在使用这个类的时候说明
            self.interation = YES;
            //手势开始是触发对应的转场操作,方法代码在后面
            [self startGesture];
            break;
        case UIGestureRecognizerStateChanged:{
            //手势过程中,通过updateInteractiveTransition设置转场过程进行的百分比,然后系统会根据百分比自动布局控件,不用我们控制了
            [self updateInteractiveTransition:persent];
            break;
        }
        case UIGestureRecognizerStateEnded:{
            //手势完成后结束标记并且判断移动距离是否过半,过则finishInteractiveTransition完成转场操作,否者取消转场操作,转场失败
            self.interation = NO;
            if (persent > 0.5) {
                [self finishInteractiveTransition];
            }else{
                [self cancelInteractiveTransition];
            }
            break;
        }
        default:
            break;
         }
        }  
        //触发对应转场操作的代码如下,根据type(type是我自定义的枚举值)我们去判断是触发哪种操作,对于push和present由于要传入需要push和present的控制器,为了解耦,我用block把这个操作交个控制器去做了,让这个手势过渡管理者可以充分被复用
        - (void)startGesture{
        switch (_type) {
        case XWInteractiveTransitionTypePresent:{
            if (_presentConifg) {
                _presentConifg();
            }
        }
            break;
            
        case XWInteractiveTransitionTypeDismiss:
            [_vc dismissViewControllerAnimated:YES completion:nil];
            break;
        case XWInteractiveTransitionTypePush:{
            if (_pushConifg) {
                _pushConifg();
            }
        }
            break;
        case XWInteractiveTransitionTypePop:
            [_vc.navigationController popViewControllerAnimated:YES];
            break;
          }
        }  

7、 手势过渡管理者就算完毕了,这个手势管理者可以用到其他任何的模态和导航控制器转场中,以后都不用在写了,现在把他用起来,在vc2和vc1中创建相应的手势过渡管理者,并放到相应的代理方法去返回它

        //创建dismiss手势过渡管理者,present的手势过渡要在vc1中创建,因为present的手势是加载vc1的view上的,我选择通过代理吧vc1中创建的手势过渡管理者传过来
        self.interactiveDismiss = [XWInteractiveTransition interactiveTransitionWithTransitionType:XWInteractiveTransitionTypeDismiss           GestureDirection:XWInteractiveTransitionGestureDirectionDown];
            [self.interactiveDismiss addPanGestureForViewController:self];
         [_interactivePush addPanGestureForViewController:self.navigationController];
            //返回dissmiss的手势过渡管理
        - (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:      (id<UIViewControllerAnimatedTransitioning>)animator{
            //在没有用手势触发的dismiss的时候需要传nil,否者无法点击dimiss,所以interation就是用来判断是否是手势触发转场的
            return _interactiveDismiss.interation ? _interactiveDismiss : nil;
        }
        
        //返回present的手势管理,这个手势管理者是在vc1中创建的,我用代理传过来的
        - (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:       (id<UIViewControllerAnimatedTransitioning>)animator{
            XWInteractiveTransition *interactivePresent = [_delegate interactiveTransitionForPresent];
            return interactivePresent.interation ? interactivePresent : nil;
        }  

8、 终于完成了,再来看一下效果,是不是还不错!

弹性pop

DEMO TWO

1、 创建动画过渡管理者的代码就不重复说明了,我仿造demo1,利用枚举创建了一个同时管理push和pop的管理者,然后动画的逻辑代码集中在doPushAnimationdoPopAnimation中,很多内容都在demo1中说明了,下面的注释就比较简单了,来看看

        //Push动画逻辑
        - (void)doPushAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
        XWMagicMoveController *fromVC = (XWMagicMoveController *)[transitionContext     viewControllerForKey:UITransitionContextFromViewControllerKey];
        XWMagicMovePushController *toVC = (XWMagicMovePushController *)[transitionContext   viewControllerForKey:UITransitionContextToViewControllerKey];
        //拿到当前点击的cell的imageView
        XWMagicMoveCell *cell = (XWMagicMoveCell *)[fromVC.collectionView cellForItemAtIndexPath:fromVC.currentIndexPath];
        UIView *containerView = [transitionContext containerView];
        //snapshotViewAfterScreenUpdates 对cell的imageView截图保存成另一个视图用于过渡,并将视图转换到当前控制器的坐标
        UIView *tempView = [cell.imageView snapshotViewAfterScreenUpdates:NO];
        tempView.frame = [cell.imageView convertRect:cell.imageView.bounds toView: containerView];
        //设置动画前的各个控件的状态
        cell.imageView.hidden = YES;
        toVC.view.alpha = 0;
        toVC.imageView.hidden = YES;
        //tempView 添加到containerView中,要保证在最前方,所以后添加
        [containerView addSubview:toVC.view];
        [containerView addSubview:tempView];
        //开始做动画
        [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 usingSpringWithDamping:0.55   initialSpringVelocity:1 / 0.55 options:0 animations:^{
            tempView.frame = [toVC.imageView convertRect:toVC.imageView.bounds toView:containerView];
            toVC.view.alpha = 1;
        } completion:^(BOOL finished) {
            //tempView先隐藏不销毁,pop的时候还会用
            tempView.hidden = YES;
            toVC.imageView.hidden = NO;
            //如果动画过渡取消了就标记不完成,否则才完成,这里可以直接写YES,如果有手势过渡才需要判断,必须标记,否则系统不会中动画完成的部署,会出现无法交互之类的bug
            [transitionContext completeTransition:YES];
            }];
        }  

    //Pop动画逻辑
        - (void)doPopAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
        XWMagicMovePushController *fromVC = (XWMagicMovePushController *)[transitionContext     viewControllerForKey:UITransitionContextFromViewControllerKey];
        XWMagicMoveController *toVC = (XWMagicMoveController *)[transitionContext   viewControllerForKey:UITransitionContextToViewControllerKey];
        XWMagicMoveCell *cell = (XWMagicMoveCell *)[toVC.collectionView cellForItemAtIndexPath:toVC.currentIndexPath];
        UIView *containerView = [transitionContext containerView];
        //这里的lastView就是push时候初始化的那个tempView
        UIView *tempView = containerView.subviews.lastObject;
        //设置初始状态
        cell.imageView.hidden = YES;
        fromVC.imageView.hidden = YES;
        tempView.hidden = NO;
        [containerView insertSubview:toVC.view atIndex:0];
        [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 usingSpringWithDamping:0.55   initialSpringVelocity:1 / 0.55 options:0 animations:^{
            tempView.frame = [cell.imageView convertRect:cell.imageView.bounds toView:containerView];
            fromVC.view.alpha = 0;
        } completion:^(BOOL finished) {
            //由于加入了手势必须判断
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
            if ([transitionContext transitionWasCancelled]) {//手势取消了,原来隐藏的imageView要显示出来
                //失败了隐藏tempView,显示fromVC.imageView
                tempView.hidden = YES;
                fromVC.imageView.hidden = NO;
            }else{//手势成功,cell的imageView也要显示出来
                //成功了移除tempView,下一次pop的时候又要创建,然后显示cell的imageView
                cell.imageView.hidden = NO;
                [tempView removeFromSuperview];
            }
          }];
        }   

2、 然后将这个动画过渡管理者和demo1中创建的手势过渡管理者分别放到正确的代理方法中,用起来就可以了

神奇移动

DEMO THREE

1、 直接看看doPushAnimationdoPopAnimation的动画逻辑,这次使用了CAGradientLayer给动画的过程增加了阴影

    //Push动画逻辑
    - (void)doPushAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    //还是使用截图大法来完成动画,不然还是会有奇妙的bug;
    UIView *tempView = [fromVC.view snapshotViewAfterScreenUpdates:NO];
    tempView.frame = fromVC.view.frame;
    UIView *containerView = [transitionContext containerView];
    //将将要动画的视图加入containerView
    [containerView addSubview:toVC.view];
    [containerView addSubview:tempView];
    fromVC.view.hidden = YES;
    [containerView insertSubview:toVC.view atIndex:0];
    //设置AnchorPoint,并增加3D透视效果
    [tempView setAnchorPointTo:CGPointMake(0, 0.5)];
    CATransform3D transfrom3d = CATransform3DIdentity;
    transfrom3d.m34 = -0.002;
    containerView.layer.sublayerTransform = transfrom3d;
    //增加阴影
    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;
    [tempView 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:^{
        //翻转截图视图
        tempView.layer.transform = CATransform3DMakeRotation(-M_PI_2, 0, 1, 0);
        //给阴影效果动画
        fromShadow.alpha = 1.0;
        toShadow.alpha = 0.0;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        if ([transitionContext transitionWasCancelled]) {
            //失败后记得移除截图,下次push又会创建
            [tempView removeFromSuperview];
            fromVC.view.hidden = NO;
        }
    }];
}}
    //Pop动画逻辑
    - (void)doPopAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    //拿到push时候的的截图视图
    UIView *tempView = containerView.subviews.lastObject;
    [containerView addSubview:toVC.view];
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        //把截图视图翻转回来
        tempView.layer.transform = CATransform3DIdentity;
        fromVC.view.subviews.lastObject.alpha = 1.0;
        tempView.subviews.lastObject.alpha = 0.0;
    } completion:^(BOOL finished) {
        if ([transitionContext transitionWasCancelled]) {
            [transitionContext completeTransition:NO];
        }else{
            [transitionContext completeTransition:YES];
            [tempView removeFromSuperview];
            toVC.view.hidden = NO;
        }
    }];}

2、 最后用上去在加上手势就是这个样子啦

翻页效果

DEMO FOUR

1、 直接看看doPresentAnimationdoDismissAnimation的动画逻辑,这次使用了CASharpLayer和UIBezierPath

    //Present动画逻辑
    - (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    //拿到控制器获取button的frame来设置动画的开始结束的路径
    UINavigationController *fromVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    XWCircleSpreadController *temp = fromVC.viewControllers.lastObject;
    UIView *containerView = [transitionContext containerView];
    [containerView addSubview:toVC.view];
    //画两个圆路径
    UIBezierPath *startCycle =  [UIBezierPath bezierPathWithOvalInRect:temp.buttonFrame];
    //通过如下方法计算获取在x和y方向按钮距离边缘的最大值,然后利用勾股定理即可算出最大半径
    CGFloat x = MAX(temp.buttonFrame.origin.x, containerView.frame.size.width - temp.buttonFrame.origin.x);
    CGFloat y = MAX(temp.buttonFrame.origin.y, containerView.frame.size.height - temp.buttonFrame.origin.y);
    //勾股定理计算半径
    CGFloat radius = sqrtf(pow(x, 2) + pow(y, 2));
    //以按钮中心为圆心,按钮中心到屏幕边缘的最大距离为半径,得到转场后的path
    UIBezierPath *endCycle = [UIBezierPath bezierPathWithArcCenter:containerView.center radius:radius startAngle:0 endAngle:M_PI * 2 clockwise:YES];
    //创建CAShapeLayer进行遮盖
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    //设置layer的path保证动画后layer不会回弹
    maskLayer.path = endCycle.CGPath;
    //将maskLayer作为toVC.View的遮盖
    toVC.view.layer.mask = maskLayer;
    //创建路径动画
    CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    maskLayerAnimation.delegate = self;
    //动画是加到layer上的,所以必须为CGPath,再将CGPath桥接为OC对象
    maskLayerAnimation.fromValue = (__bridge id)(startCycle.CGPath);
    maskLayerAnimation.toValue = (__bridge id)((endCycle.CGPath));
    maskLayerAnimation.duration = [self transitionDuration:transitionContext];
    maskLayerAnimation.delegate = self;
    //设置淡入淡出
    maskLayerAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [maskLayerAnimation setValue:transitionContext forKey:@"transitionContext"];
    [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];
}

    //Dismiss动画逻辑
    - (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UINavigationController *toVC = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    XWCircleSpreadController *temp = toVC.viewControllers.lastObject;
    UIView *containerView = [transitionContext containerView];
    //画两个圆路径
    CGFloat radius = sqrtf(containerView.frame.size.height * containerView.frame.size.height + containerView.frame.size.width * containerView.frame.size.width) / 2;
    UIBezierPath *startCycle = [UIBezierPath bezierPathWithArcCenter:containerView.center radius:radius startAngle:0 endAngle:M_PI * 2 clockwise:YES];
    UIBezierPath *endCycle =  [UIBezierPath bezierPathWithOvalInRect:temp.buttonFrame];
    //创建CAShapeLayer进行遮盖
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.fillColor = [UIColor greenColor].CGColor;
    maskLayer.path = endCycle.CGPath;
    fromVC.view.layer.mask = maskLayer;
    //创建路径动画
    CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    maskLayerAnimation.delegate = self;
    maskLayerAnimation.fromValue = (__bridge id)(startCycle.CGPath);
    maskLayerAnimation.toValue = (__bridge id)((endCycle.CGPath));
    maskLayerAnimation.duration = [self transitionDuration:transitionContext];
    maskLayerAnimation.delegate = self;
    maskLayerAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [maskLayerAnimation setValue:transitionContext forKey:@"transitionContext"];
    [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];
}

2、最后在animationDidStop的代理方法中处理到动画的完成逻辑,处理方式都类似

    - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    switch (_type) {
        case XWCircleSpreadTransitionTypePresent:{
            id<UIViewControllerContextTransitioning> transitionContext = [anim valueForKey:@"transitionContext"];
            [transitionContext completeTransition:YES];
            [transitionContext viewControllerForKey:UITransitionContextToViewKey].view.layer.mask = nil;
        }
            break;
        case XWCircleSpreadTransitionTypeDismiss:{
            id<UIViewControllerContextTransitioning> transitionContext = [anim valueForKey:@"transitionContext"];
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
            if ([transitionContext transitionWasCancelled]) {
                [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view.layer.mask = nil;
            }
        }
            break;
    }
}

3、 最后用上去在加上手势就是这个样子啦

扩散效果

总结

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

相关文章

网友评论

  • BeeMifeng:demo one vc2中实现的代理方法中,用的是类方法。怎么做到的初始化成员变量 _type?
  • TMMMMMS:demo one第五步中有个地方没有看懂, - (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext方法中你说toVC是vc1,fromVC就是vc2,在添加视图到containerView处,“将截图视图和vc2的view都加入ContainerView中”,vc2不是fromVC,但是你代码写的的是toVC.view
  • __阳阳:膜拜大神, 问下能不能使用push实现DEMO ONE中的弹性的present动画,支持手势present和dismiss 的效果?
  • BETOMElo:好文章 收藏了
  • p_peng:666
  • NotFunGuy:楼主写的很棒啊
  • 8814d8c64dab:您好,我按照您的讲解写了一个demo,第一个动画的。但是pan手势不能拖到view,只能开启动画。您的demo放手的时候才会继续完成动画。
    8814d8c64dab:就是拖动的时候,代码会立即执行完设置的过渡动画,而不是随着拖动,动画的进度可以控制。
  • 每天都被菜醒:小圆点的手势控制有问题了,控制不了动画的进度,是怎么回事
    8814d8c64dab:我也遇到了,你解决了吗。请教一下。
  • CloudL:暂时用不上,先标记着,注释写得很好,不错
  • ldldlkdldld:想请教一个问题,modal,模态到底指的是什么意思呢?
  • Society2012: 小伙,bug挺多的的!
  • Mr卿:pop回来后 屏幕 不能点击了。。😓
  • 雪碧童鞋:翻页的时候导航栏会出现重叠效果,这个怎么去除
  • Hanfank:文章写得非常好,我也有个问题,我modal出来的vc是有导航nav的,弹出来之后在presend页面点击进入下一页,视图就变成透明了,没有任何视图。求解
  • 坐着窜天猴上天: UIView * fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    在弹性POP里面,这个值是NIL。但你要是取fromVC.View 的话确实是存在的,两个值不一样?
  • 睿少:我可以实现就是类似modal的转场不?不过VC弹出是从上而下
  • 苏坡乔:感谢,好文,学习了
  • 九剑仙:我问个问题哈,比如说,我用自定义的模态动画,竖屏状态下present到下一个VC,然后我把手机横着拿,在横屏状态dismiss回来,然后视图显示就出错了。但是用系统的模态动画,就不会出现这种问题,是不是哪个环节少了些什么。在线等,挺急的~~~
    花生儿:@九剑仙 竖屏切换的横屏返回的时候,代理方法里面的几个frame值变化了,感觉应该不需要考虑横竖屏截图问题。
  • Fire_day:虽说没看懂,但是感觉很高大上的样子~
  • 水寒不知:为什么我看onevcat大神的代理方法UIViewControllerTransitioningDelegate都是写在vc1.中的
  • 豆瓣菜:mark 动画
  • 豆瓣菜:mark 动画
  • l富文本l:另加一句,感谢作者提供的学习资料!
  • l富文本l:snapshotViewAfterScreenUpdates该方法在iphone7模拟器上空白,作者知道什么问题吗?
    花生儿:@lcying 最近在做这个,遇到的这个问题应该是上述提到的方法失效了。需要自己写个补丁方法来截取图片。如果有问题,可以联系我讨论下。
  • 松树李树:总是先白屏一下,v c1的视图总是消失
  • 蒋昉霖:xib能用么
  • 1a033c74f1c1:demo 在哪里能下载 只有这些代码片段吗 ??
  • 李国安:先点个喜欢吧 效果不错
  • 语安月月鸟:很好!
  • JimmyOu:问一下博主,为什么最后一个圆点转场的一个VC会是UINavigationController?,其它三个动画从transitionContext取出的fromVC和toVC都是自定义的VC?
  • mojue:mark
  • 480a52903ce5:作者很用心, 学习了,谢谢 :+1:
  • luckyCode:请问一下,转场后怎样在实现push进入下一页面?谢谢
    a15aeda87097:你解决的了吗?
    a15aeda87097:我也遇到这个问题了
  • imChay:成为百分比手势过渡管理对象 -> 称为百分比手势过渡管理对象
    wazrx:@whyCoder thx,转场新文章已经发布:http://www.jianshu.com/p/e498b956491c,欢迎提意见
  • kuai空调:当手势执行到一半离开屏幕,view回到初始状态这个过程是没有动画的,很生硬。除了翻页那个效果没有这个问题,其它三个好像都有这个问题,请问作者知道是怎么回事吗?我搞了半天也没想出办法。可以参见Apple music的当前歌曲页面的效果。
    wazrx:@讨厌西红柿 我也考虑到过displaylink,我正在想一个比较优雅的做法,有点思路了
    讨厌西红柿:@wazrx :grin: 我用另一种方法实现,解决了松手后没有动画并且会闪一下的问题。使用displaylink,先添加一个uiview,view的高为圆的半径,以这个view的高做动画,从最小的半径到最大的半径。然后,displaylink回调中,使用这个view的高为半径画圆。这样便可以解决松手没有动画及会闪一下的问题,不过有稍许的不流畅,displaylink没有按期望一秒跑60次。
    wazrx:@飞烟灰灭 好像只有小圆点扩散效果有这个问题吧,我想想有没有好点的方法,好久没折腾转场了o(╯□╰)o
  • kuai空调:有个问题没想出解决办法,就是手势到中途取消,view回到初始状态这个过程是没有动画的,很生硬,作者知道如何在转场取消后动画回到初始状态吗?可以参见Apple music当前播放歌曲的页面效果。
  • jzhang:注释感人!
  • 讨厌西红柿:圈圈放大缩小的转场动画,在手势取消后会闪一下,调了一天都木有解决。找了其他的实现方式,都是大同小异,该闪还是会闪,不知博主能否解决?
  • _东阁堂主_:在tabbar上开发,各种奇怪的问题就出现了。
    angBiu:@舸东渡 恩 是的 会莫名其妙崩溃在 self.tabbar = 0 0是这个转场动画的 fromvc所在tabbar位置
  • cfb9d8b0d5cb:为什么在demo1中要通过delegate方法在vc1中使vc2进行dismiss,vc1不会黑屏,在vc2中直接dismiss会黑屏
  • 四月天__:哥们 你好 我学习你的demo之后 自己实现自定义模态弹出的时候,toVC的view 弹出之后,fromVC的view消失了 麻烦指教下
  • 52b47abbb6db:6死了
  • d053345b0b60:代码中的:UIView *tempView = subviewsArray[MIN(subviewsArray.count, MAX(0, subviewsArray.count - 2))]; 这句是什么意思啊?由于首先添加的就是那个截图的tempView,所以访问它的时候直接写成:subviewsArray[0]; 才对吧,为什么要用MIN和MAX呢?
    wazrx:@Smile_521 iOS7中视图层级有些变化,如果直接使用0会报错
  • qBryant:按照你的例子做了一遍,present后面的VC截图后,截图上的navigationBar是黑色的,这是什么原因?求教!
  • qBryant:比较详细,值得学习。。。 :+1:
  • gjgoodjob:学习了!
  • 鹤鹤:啥都没改,embed in navigation controller ,跑一下没问题。再把 navigation controller删掉再跑,也不会黑屏。。。。我无语了到底是啥原因黑屏的
  • 鹤鹤:self.modalPresentationStyle = UIModalPresentationCustom 设置之后,dissmiss结束,VC1看不见了,黑屏,不是LZ的demo。
    不设置,dismiss结束,看得见VC1,甚至还不用在dissmiss里写self.containerView?.addSubview(self.toViewController!.view)。
    是lZ套了navigationcontroller的原因吗
  • BUn_7:跟着学习
  • 莫须有恋:楼主好,照着敲了一遍代码,有几个问题,想问一下楼主。
    1.self.modalPresentationStyle = UIModalPresentationCustom没有设置的话确实会造成presentVC被移除,需要dimiss时再添加(即使不添加也没问题只是会有一个淡出的动画),但是我测试的时候如果设置了的话,dismiss结束后presentVC也消失了。
    2.翻页的动画Demo,我写完之后,push动画完成的下个界面的self.view显示不正确,frame就像被重新设置过一样。如果有人遇到相同问题,希望能回答下,感谢。
    莫须有恋:@wazrx 运行你的没问题。第一个问题我试了很多遍,感觉还是不设置self.modalPresentationStyle = UIModalPresentationCustom最好,在dismiss结束添加,会少不少bug。第二个不知道什么情况,我只好在push的下个界面的viewdidLoad中有重新设置了self.view的frame,不知道是不是我使用xib的原因
    wazrx:@莫须有恋 你运行demo有问题吗?
  • ziujio:最近在学动画,先Mark下
  • 4aec6b0a15de:靠谱!
  • 顾夕城:mark :grin:
  • 5ac74cdba72f:小圆点扩散那个会有个向上滑动闪屏的现象,请问我怎么设置可以避免这种现象,例如取消向上滑动的手势响应还是要怎么写?
  • 5ac74cdba72f:ios9.2测试效果发现手势响应结果不是很稳定,例如弹性的效果:向上滑动的时候弹窗视图不是稳定弹出的
    会发现弹出后又缩回去的
    wazrx:@逸尘_ 用真机我自己感觉还好-_-||用真机跑吧
    5ac74cdba72f:@wazrx 是好了点,不过向上滑动总感觉不顺滑,向下滑动就很好.不过我对过场动画不是很了解,没有自己写过动画,不知道是不是自定义的动画有这样的问题是不是正常的
    wazrx:这是因为整个弹簧效果回弹占用了很长时间比,手势成功百分比不能线性的算成0.5,这个比例在弹簧效果中调成0.3就好多了
  • 与伟大LEE同行:iOS7系统下 转场会黑屏 什么都不显示 不知道你发现了没
    与伟大LEE同行:@wazrx 方便给个Q吗 有时间交流交流
    与伟大LEE同行:@wazrx 好的 我现在做的项目有用到你的那个弹性pop的效果 刚才测试给我发报告说iOS7直接黑屏了
    wazrx:@与伟大LEE同行 没有测过iOS7 找个时间看看
  • 0f027546819b:很不错 Mark
  • 小坏蛋L:吊炸天!
  • 拥抱月亮的大星星:Iphone5s运行demo有好多地方直接闪退,不过值得学习
    与伟大LEE同行:@wazrx iOS7下小圆点扩散会崩
    [transitionContext viewControllerForKey:UITransitionContextToViewKey].view.layer.mask = nil;
    蹦在这句
    wazrx:@Vefing 谢谢,不过求闪退的触发情景和控制台的错误打印,我自己测试了好多次,没有发现闪退的地方呢
  • 爱丶不失手:学习Mark
  • 垚子:666

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

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