美文网首页
iOS自定义转场动画之Pop,Push

iOS自定义转场动画之Pop,Push

作者: summerNight | 来源:发表于2018-12-07 14:44 被阅读14次

    苹果在iOS7就开放了转场动画的API,最近看了TransitionAnimation自定义转场动画这篇文章,学习了一波,决定自己做个笔记。

    以上也是引用那位老哥的图,转场的主要方法都在这了

    设置代理

    既然是要自定义转场动画,首先就是要设置代理。转场代理有三种:
    -<UINavigationControllerDelegate>
    -< UITabBarControllerDelegate >
    -< UIViewControllerTransitioningDelegate >
    你要写哪种控制器的转场,就在要转场的控制器里遵循哪种代理。我这是写的push 、pop,就遵循<UINavigationControllerDelegate>

    @interface ViewController ()<UINavigationControllerDelegate,UIViewControllerTransitioningDelegate>
    
    @end
    
    - (void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
        //保证代理不被别的控制器拿走
        self.navigationController.delegate = self;
    }
    
    - (void)viewWillDisappear:(BOOL)animated{
        [super viewWillDisappear:animated];
        self.navigationController.delegate = nil;
    }
    
    #pragma mark - UINavigationControllerDelegate
    
    - (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
        if (operation == UINavigationControllerOperationPush)
        {
            return [CustomTransition initWithType:KWTransitionTypePush];
        }
        else if (operation == UINavigationControllerOperationPop)
        {
            return [CustomTransition initWithType:KWTransitionTypePop];
        }
        return nil;
    }
    

    编写转场动画类

    这是核心部分,这个类就是实现转场各种花里胡哨的转场效果。要遵循<UIViewControllerAnimatedTransitioning>协议。一下是.h头文件:

    #import <UIKit/UIKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    typedef NS_ENUM(NSUInteger, KWTransitionType) {// 区分转场类型
        KWTransitionTypePush = 0,
        KWTransitionTypePop,
        
    };
    
    @interface CustomTransition : NSObject<UIViewControllerAnimatedTransitioning>
    
    + (instancetype)initWithType:(KWTransitionType)type;
    
    @end
    

    <UIViewControllerAnimatedTransitioning>协议有两个必须实现的方法,我们来看看这两个方法的作用,以下是.m的部分内容:

    #pragma mark - UIViewControllerAnimatedTransitioning
    
    /**
     转场动画时长
     */
    - (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{
        return 0.5;
    }
    
    /**
     执行动画
     */
    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
        switch (self.type) {
            case KWTransitionTypePush:
                [self push:transitionContext];
                break;
            case KWTransitionTypePop:
                [self pop:transitionContext];
                break;
                
            default:
                break;
        }
        
    }
    

    在写转场动画之前,我要要先知道下:转场动画的本质就是下个场景的视图(toView)替换当前场景的视图(fromView),这些动画都是在containerView里面展现的。
    举个例子:A控制器push B控制器,那么A.view就是(fromView),B.view就是(toView)。了解这些后,我们就可以写具体的转场动画了。

    Push实现

    - (void)push:(id<UIViewControllerContextTransitioning>)transitionContext{
        // 获取目标视图
        UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
        UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        
        // 将目标视图添加到容器containerView内
        UIView *contentView = [transitionContext containerView];
        [contentView addSubview:fromView];
        [contentView addSubview:toView];
        
        CGFloat width = contentView.frame.size.width;
        toView.transform = CGAffineTransformMakeTranslation(width, 0);
        
        NSTimeInterval duration = [self transitionDuration:transitionContext];
        
        [UIView animateWithDuration:duration animations:^{
            fromView.transform = CGAffineTransformMakeScale(0.9, 0.9);
            toView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            
            fromView.transform = CGAffineTransformIdentity;
            // 标记是否成功,否则系统会认为转场失败,造成无法交互
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        }];
    }
    }
    

    Pop实现

    B控制器popA控制器,这时候fromViewB.viewtoViewA.view,这点要注意下。

    - (void)pop:(id<UIViewControllerContextTransitioning>)transitionContext{
        // 获取目标视图
        UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
        UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        
        // 将目标视图添加到容器containerView内
        UIView *contentView = [transitionContext containerView];
        // 先将目标视图缩放
        toView.transform = CGAffineTransformMakeScale(0.9, 0.9);
        [contentView addSubview:toView];
        [contentView addSubview:fromView];
        
        CGFloat width = contentView.frame.size.width;
        NSTimeInterval duration = [self transitionDuration:transitionContext];
        
        [UIView animateWithDuration:duration animations:^{
            toView.transform = CGAffineTransformIdentity;
            fromView.transform = CGAffineTransformMakeTranslation(width, 0);
        } completion:^(BOOL finished) {
            
            toView.transform = CGAffineTransformIdentity;
            // 标记是否成功,否则系统会认为转场失败,造成无法交互
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        }];
    }
    

    来看看最终效果


    Untitled.gif

    但是!

    但是,单单这样实现的话,你会发现我无法用手势返回,只能点击左上角返回按钮。体验实在不好,这时候就要引入交互转场UIPercentDrivenInteractiveTransition配合手势实现。
    首先声明一个UIPercentDrivenInteractiveTransition属性。

    @property (nonatomic, strong) UIPercentDrivenInteractiveTransition *interactiveTransition;
    

    然后在给self.view添加手势

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
        [self.view addGestureRecognizer:pan];
    }
    
    - (void)pan:(UIPanGestureRecognizer *)pan{
        //产生百分比
        CGFloat process = [pan translationInView:self.view].x / ([UIScreen mainScreen].bounds.size.width);
        CGFloat xStart = [pan locationInView:self.view].x;
        // 触摸起点在50以内,才触发pop事件
        BOOL shouldPop = xStart < 50 ? YES : NO;
        if (!shouldPop) return;
    
        process = MIN(1.0,(MAX(0.0, process)));
        if (pan.state == UIGestureRecognizerStateBegan) {
            self.interactiveTransition = [UIPercentDrivenInteractiveTransition new];
            shouldPop ? [self.navigationController popViewControllerAnimated:YES] : nil;
        }
        else if (pan.state == UIGestureRecognizerStateChanged){
            [self.interactiveTransition updateInteractiveTransition:process];
        }
        else if (pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateCancelled){
            process > 0.4 ? [self.interactiveTransition finishInteractiveTransition] : [self.interactiveTransition cancelInteractiveTransition];
            self.interactiveTransition = nil;
            
        }
    }
    

    以上就可以手势返回了。但是每个控制器都要遵循<UINavigationControllerDelegate,UIViewControllerTransitioningDelegate>代理,实现代理方法,实在是多此一举,我们可以写在基类控制器里面,就不用写多余的代码了,美滋滋。
    这些笔记只是抛砖引玉,之后会跟新Modal转场。
    这里是Demo

    相关文章

      网友评论

          本文标题:iOS自定义转场动画之Pop,Push

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