iOS 自定义转场动画的那些事

iOS 7 以协议的方式开放了自定义转场的 API,协议的好处是不再拘泥于具体的某个类,只要是遵守该协议的对象都能参与转场,使其可以非常灵活的使用。转场协议由5种协议组成,实际中只需要使用其中的两个或三个便能实现绝大部分的转场动画。下面就简单讲解一下使用的心得体会,最后的总结你会发现很简单。
参考: Custom Transitions Using View Controllers
喵神的博客

TransitionVC.gif

1 概念

  • 动画控制器 (Animation Controllers) 遵守 UIViewControllerAnimatedTransitioning 协议,并且负责实际执行动画。
  • 交互控制器 (Interaction Controllers) 通过遵守 UIViewControllerInteractiveTransitioning 协议,来控制可交互式(手势或重力感应…)动画转场,大多都是使用它的一个子类UIPercentDrivenInteractiveTransition来更简单的实现手势交互动画。
  • 转场代理 (Transitioning Delegates) 根据不同的转场类型,提供需要的动画控制器和交互控制器。
    有3种转场代理:
    UINavigationControllerDelegate –自定义navigationController转场动画的时候
    UITabBarControllerDelegate –自定义tabbarController转场动画的时候
    UIViewControllerTransitioningDelegate–自定义present/dismiss的时候
  • 转场上下文 (Transitioning Context) 提供转场中需要的数据,比如在转场过程中所参与的视图控制器和视图的相关属性。 转场上下文对象遵守 UIViewControllerContextTransitioning 协议,并且这是由系统负责生成和提供的。
    转场协调器(Transition Coordinators) 可以在运行转场动画时,并行的运行其他动画。转场协调器遵守UIViewControllerTransitionCoordinator 协议

2 自定义转场动画时你可能用到的那些方法

.
UIViewControllerContextTransitioning

这个接口用来提供切换的上下文给开发者使用,包含了从哪个VC到哪个VC等各类信息,一般不需要开发者自己实现。具体来说,iOS7的自定义切换目的之一就是切换相关代码解耦,在进行VC切换时,做切换效果实现的时候必须需要 切换前后VC的一些信息,提供一些方法,以供我们使用。

-(UIView *)containerView; 
>VC切换所发生的view容器,开发者应该将切出的view移除,将切入的view加入到该view容器中。
-(UIViewController *)viewControllerForKey:(NSString *)key; 
>提供一个key,返回对应的VC。现在的SDK中key的选择只有UITransitionContextFromViewControllerKey和UITransitionContextToViewControllerKey两种,分别表示将要切出和切入的VC。
 -(CGRect)initialFrameForViewController:(UIViewController *)vc; 
>某个VC的初始位置,可以用来做动画的计算。
-(CGRect)finalFrameForViewController:(UIViewController *)vc;
> 与上面的方法对应,得到切换结束时某个VC应在的frame。
-(void)completeTransition:(BOOL)didComplete; 
>向这个context报告切换已经完成。

UIViewControllerAnimatedTransitioning

这个接口负责切换的具体内容,即“切换中应该发生什么”。开发者在做自定义切换效果时大部分代码会是用来实现这个接口。它只有两个方法需要我们实现:

-(NSTimeInterval)transitionDuration:(id < UIViewControllerContextTransitioning >)transitionContext; 
>系统给出一个切换上下文,我们根据上下文环境返回这个切换所需要的花费时间(一般就返回动画的时间就好了,系统会用这个时间来在百分比驱动的切换中进行帧的计算)。
-(void)animateTransition:(id < UIViewControllerContextTransitioning >)transitionContext; 
>在进行切换的时候将调用该方法,我们对于切换时的UIView的设置和动画都在这个方法中完成。

UIViewControllerTransitioningDelegate

这个接口的作用比较简单单一,在需要VC切换的时候系统会像实现了这个接口的对象询问是否需要使用自定义的切换效果。这个接口共有四个类似的方法:

-(id< UIViewControllerAnimatedTransitioning >)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source;
>在 presented 动画中会被调用
-(id< UIViewControllerAnimatedTransitioning >)animationControllerForDismissedController:(UIViewController *)dismissed;
>在 dismiss 动画中会被调用
-(id< UIViewControllerInteractiveTransitioning >)interactionControllerForPresentation:(id < UIViewControllerAnimatedTransitioning >)animator;
-(id< UIViewControllerInteractiveTransitioning >)interactionControllerForDismissal:(id < UIViewControllerAnimatedTransitioning >)animator;

UIPercentDrivenInteractiveTransition
这是一个实现了UIViewControllerInteractiveTransitioning接口的类,为我们预先实现和提供了一系列便利的方法,可以用一个百分比来控制交互式切换的过程。一般来说我们更多地会使用某些手势来完成交互式的转移,这样使用这个类(一般是其子类,下面会讲到)的话就会非常方便。我们在手势识别中只需要告诉这个类的实例当前的状态百分比如何,系统便根据这个百分比和我们之前设定的迁移方式为我们计算当前应该的UI渲染,十分方便。具体的几个重要方法:

-(void)updateInteractiveTransition:(CGFloat)percentComplete
> 更新百分比,一般通过手势识别的长度之类的来计算一个值,然后进行更新。之后的例子里会看到详细的用法
-(void)cancelInteractiveTransition 
>报告交互取消,返回切换前的状态
–(void)finishInteractiveTransition 
>报告交互完成,更新到切换后的状态

UINavigationControllerDelegate

自定义navigationController转场动画的时候

- (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);
>视图控制器转换返回一个互动的动画对象使用。

3 实战

  • Present 动画

就如上面所说转场动画遵循UIViewControllerAnimatedTransitioning协议拿到需要做动画的视图,首先建一个动画类遵循这个协议。

@interface BouncePresentAnimation : NSObject <UIViewControllerAnimatedTransitioning>

遵循这个协议后实现里面的两个方法
方法1:用来控制转场动画的时间

  - (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext
{
    return 0.8f;
}

方法2:这里用来控制视图切换做动画,因为有 present 和 dismiss 所以在这里区分两个动画(需要一个type,后面会提到)
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
switch (self.type)
{
case TransitionTypePresent:
[self presentAnimation:transitionContext];
break;
case TransitionTypeDissmiss:
[self dismissAnimation:transitionContext];
break;
default:
break;
}
}
实现:具体也可以看 喵神的博客 此处为借鉴,旨在理解。

//实现present动画逻辑代码
     \\- (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
{
    // 1. Get controllers from transition context
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];

    //fromVC.view.hidden = YES;

    UIView * screenSnapShotView = [fromVC.view snapshotViewAfterScreenUpdates:YES];

    // 2. Set init frame for toVC
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    CGRect finalFrame = [transitionContext finalFrameForViewController:toVC];
    toVC.view.frame = CGRectOffset(finalFrame, 0, screenBounds.size.height);

    // 3. Add toVC's view to containerView
    UIView *containerView = [transitionContext containerView];

    [containerView insertSubview:screenSnapShotView aboveSubview:fromVC.view];

    [containerView addSubview:toVC.view];

    // 4. Do animate now
    NSTimeInterval duration = [self transitionDuration:transitionContext];

    [UIView animateWithDuration:duration
                          delay:0.0
         usingSpringWithDamping:0.6
          initialSpringVelocity:0.0
                        options:UIViewAnimationOptionTransitionFlipFromBottom
                     animations:^{
                         toVC.view.frame = finalFrame;
                     } completion:^(BOOL finished) {
                         // 5. Tell context that we completed.
                         [transitionContext completeTransition:YES];
                     }];

}
//实现dismiss动画逻辑代码
- (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
{
    
    // 1. Get controllers from transition context
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    // 2. Set init frame for fromVC
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    CGRect initFrame = [transitionContext initialFrameForViewController:fromVC];
    CGRect finalFrame = CGRectOffset(initFrame, 0, screenBounds.size.height);
    
    // 3. Add target view to the container, and move it to back.
    UIView *containerView = [transitionContext containerView];
    [containerView addSubview:toVC.view];
    [containerView sendSubviewToBack:toVC.view];
    
    // 4. Do animate now
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    [UIView animateWithDuration:duration animations:^{
        fromVC.view.frame = finalFrame;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}

上面我们完成了动画部分,接下来就是要告知系统,让其去使用我们的动画。就如上面提到的需要实现UIViewControllerTransitioningDelegate,在这里你会知道present和dismiss,所以在这里你可以传个type告知你需要的是那种动画,从而让你的动画类去实现相应动画。
present 时会触发的代理,这个时候告诉它我们需要的present动画

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [BouncePresentAnimation transitionWithTransitionType:TransitionTypePresent];
}

dismiss 时会触发的代理,这个时候告诉它我们需要的dismiss动画

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [BouncePresentAnimation transitionWithTransitionType:TransitionTypeDissmiss];
}

当然前提是你遵从了它的代理,你可以让前一个控制器作为后者的代理去实现这些方法。

 ModalViewController *mvc =  [[ModalViewController alloc] init];
 mvc.transitioningDelegate = self;
 mvc.delegate = self;
 [self presentViewController:mvc animated:YES completion:nil];
  • pop 动画

和present一样,如果想要自定义动画,需要遵循UIViewControllerAnimatedTransitioning协议

@interface PushAnimation : NSObject<UIViewControllerAnimatedTransitioning>

同样的实现协议里的两个方法

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    return 1.0f;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    self.transitionContext = transitionContext;
    
    switch (self.type)
    {
        case TransitionAnimTypePop:
            [self transitionAnimTypePopWithTransitionContext:transitionContext];
            break;
        case TransitionAnimTypePush:
             [self transitionAnimTypePushWithTransitionContext:transitionContext];
            break;
        default:
            break;
    }
    
}

同样的,你需要遵守 UINavigationControllerDelegate ,并在它的代理方法里面实现你要的动画
添加代理

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.delegate = self;
}

实现动画

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

        return [PushAnimation transitionWithTransitionType:
                TransitionAnimTypePush];
    }
    else if (operation == UINavigationControllerOperationPop)
    {
        return [PushAnimation transitionWithTransitionType:
                        TransitionAnimTypePop];

    }
    //返回nil则使用默认的动画效果
    return nil;
}
  • 实现手势动画

如上所述,手势动画需要 UIPercentDrivenInteractiveTransition实现,提供了一系列便利的方法,可以用一个百分比来控制交互式切换的过程。我们在手势识别中只需要告诉这个类的实例当前的状态百分比如何,系统便根据这个百分比和我们之前设定的迁移方式为我们计算当前应该的UI渲染,使动画过渡的更加自然。
首先我们新建一个手势处理类SwipeUpInteractiveTransition继承于UIPercentDrivenInteractiveTransition这样我们可以获取相应的父类方法。
首先给所在的控制器的view添加手势

[self.transitionController wireToViewController:mvc];

主要运用的手势控制

- (void)handleGesture:(UIPanGestureRecognizer *)gestureRecognizer {
    CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view.superview];
    switch (gestureRecognizer.state)
    {
        case UIGestureRecognizerStateBegan:
            // 1. Mark the interacting flag. Used when supplying it in delegate.
            self.interacting = YES;
            [self.presentingVC dismissViewControllerAnimated:YES completion:nil];
            break;
        case UIGestureRecognizerStateChanged:
        {
            // 2. Calculate the percentage of guesture
            CGFloat fraction = (translation.y / KWindowHeight);
            //Limit it between 0 and 1
            fraction = fminf(fmaxf(fraction, 0.0), 1.0);
            NSLog(@"fraction==%f",fraction);
            self.shouldComplete = (fraction > 0.5);
            [self updateInteractiveTransition:fraction];
            break;
        }
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
        {
            // 3. Gesture over. Check if the transition should happen or not
            self.interacting = NO;
            if (!self.shouldComplete || gestureRecognizer.state == UIGestureRecognizerStateCancelled)
            {
                [self cancelInteractiveTransition];
            }
            else
            {
                [self finishInteractiveTransition];
            }
            break;
        }
        default:
            break;
    }
}
  • 总结
    非交互动画
    1.创建动画类遵从UIViewControllerAnimatedTransitioning 实现里面的接口
    2.让相应的控制器做代理
    3.present 实现 UIViewControllerTransitioningDelegate 接口,push 实现 UINavigationControllerDelegate 接口
    交互动画
    1.创建动画类继承于 UIPercentDrivenInteractiveTransition ,然后在里面实现相应的动画即可。
    2.在跳转页面时告诉动画类你需要控制的页面

注:在push动画中的layer动画可以任意替换为其他转场动画,只用把动画加到 containerView.layer 上即可。CATransition 动画传送门

containerView.layer addAnimation:transition forKey:nil`

照例放Demo,仅供参考
Demo地址:
https://github.com/yongliangP/iOS-TransitionVC
如果你觉得对你有帮助请点喜欢哦,也可以关注我,每周至少一篇技术。
或者关注 我的专题 每周至少5篇更新,多谢支持哈。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • 前言 正如标题所示,iOS开发中, 自定义转场的过渡动画确实是必须要了解的, 在iOS7之后实现也是很简单的. 如...
    ZeroJ阅读 8,803评论 9 122
  • OC开发我们主要有以下三种自定义方法,供大家参考:Push & PopModalSegue 前两种大家都很熟悉,第...
    ScaryMonsterLyn阅读 1,540评论 1 3
  • 前言的前言 唐巧前辈在微信公众号「iOSDevTips」以及其博客上推送了我的文章后,我的 Github 各项指标...
    VincentHK阅读 5,241评论 4 44
  • 只有圆周 转动许久之后 仍在徘徊 只因初心如磐 指针转动 不同的角度 钟点刻记 皆是过客罢 非一主擒之 此心终了 之后
    萍风衣旧阅读 233评论 0 1
  • 有志者,事竞成。下面是我这段时间经过深入思考后列出的一些人生计划,希望自己从下周开始就调整状态,坚持不懈地完成以下...
    紫丁香68阅读 173评论 0 0