一张图看懂 iOS 转场动画

转场动画在iOS开发中非常常见, 其原理大概如下图:

TransitionAnimation.png

一切都是从图中的 *** Transition Animation *** 开始.

本文主要基于以上这张图, 讲解了transitionFromViewController, CATransition, TransitionAnimation三种转场实现方式.

transitionFromViewController

我们可以先看UIViewController自带的方法:
transitionFromViewController:toViewController:duration:options:animations:completion:
参数很多, 不过都非常直观.
通常的使用场景是 在多个Child ViewController之间切换.

AViewController *a = self.childViewControllers[0];
BViewController *b = self.childViewControllers[1];
CViewController *c = self.childViewControllers[2];

// Curl 翻页效果
// UIViewAnimationOptionTransitionCurlUp, UIViewAnimationOptionTransitionCurlDown
// Flip 翻转效果
// UIViewAnimationOptionTransitionFlipFromLeft, UIViewAnimationOptionTransitionFlipFromRight
// UIViewAnimationOptionTransitionFlipFromTop, UIViewAnimationOptionTransitionFlipFromDown

[self transitionFromViewController:_currentViewController
                  toViewController:b
                          duration:0.5
                           options:UIViewAnimationOptionTransitionFlipFromRight
                        animations:^{

} completion:^(BOOL finished) {

}];

转场的效果可以通过options和animations参数来控制.

NewsNavigationBar

屏幕快照 2016-08-15 21.34.01.png

这个demo是利用transitionFromViewController方法实现的类似网易新闻的导航栏样式.
DemoNewsNavigationBar

CATransition

CATransition继承自CALayer, 包含了一些场景的动画效果. 如Fade,Cube,Ripple,PageCurl,CameraIrilHollow等.
使用如下:

CATransition *animation = [CATransition animation];
animation.duration = 0.5;
animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
animation.type = kCATransitionFade;

// 在当前view上执行CATransition动画
// [self.view.layer addAnimation:animation forKey:@"animation"];

// 在window上执行CATransition, 即可在ViewController转场时执行动画。
[self.view.window.layer addAnimation:animation forKey:@"kTransitionAnimation"];

DemoCATransitionPresentedViewController *presentedVC = [[DemoCATransitionPresentedViewController alloc] init];
[self presentViewController:presentedVC animated:NO completion:nil];

如果仅仅在当前view的layer上添加该动画, 则使用场景不在本文讨论范围之内.
而将该动画添加到window.layer上, 则会在执行present或push操作时, 呈现指定的转场动画效果.

[self.navigationController.view.layer addAnimation:animation forKey:@"kTransitionAnimation"];

DemoCATransitionPushedViewController *pushedVC = [[DemoCATransitionPushedViewController alloc] init];
[self.navigationController pushViewController:pushedVC animated:NO];

Transition Animation

iOS中自定义的转场动画, 通常需要两个对象.

UIViewControllerTransitioningDelegate

继承该协议的对象是transition的代理, 该协议中主要指定了present/dismiss的UIViewControllerAnimatedTransitioning对象.

DemoViewControllerTransitionPresentedViewController *presentedVC = [[DemoViewControllerTransitionPresentedViewController alloc] init];
presentedVC.transitionDelegate = self;
[self presentViewController:presentedVC animated:YES completion:nil];

该协议包含的方法:

//       prenent       
- (id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source;
//       pop       
- (id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed;
//       prenent       
- (id <UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id <UIViewControllerAnimatedTransitioning>)animator;
//       pop       
- (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id <UIViewControllerAnimatedTransitioning>)animator;

前两个方法都返回的是继承UIViewControllerAnimatedTransitioning协议的对象,其中即为转场动画的细节实现。

UIViewControllerAnimatedTransitioning

实现该协议的对象中即包含了转场动画的细节实现代码, 因此, UIViewControllerTransitioningDelegate对象的作用主要是指定了包含转场动画细节实现的对象.
UIViewControllerAnimatedTransitioning包含的方法主要有:

转场动画时间

// This is used for percent driven interactive transitions, as well as for container controllers that have companion animations that might need to synchronize with the main animation.
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext;

动画结束回调方法

@optional

// This is a convenience and if implemented will be invoked by the system when the transition context's completeTransition: method is invoked.
- (void)animationEnded:(BOOL) transitionCompleted;

转场动画细节实现

该方法中则主要负责转场动画细节的实现.

// This method can only  be a nop if the transition is interactive and not a percentDriven interactive transition.
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext;

转场细节中的几个关键变量:

_transitionContext = transitionContext;

_containerView = [transitionContext containerView];

_from = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
_to = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

// iOS8之后才有
if ([transitionContext respondsToSelector:@selector(viewForKey:)]) {
    _fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    _toView = [transitionContext viewForKey:UITransitionContextToViewKey];
} else {
    _fromView = _from.view;
    _toView = _to.view;
}

containerView即是转场过程中呈现出来的View.
我们能够从transitionContext中获取到fromView和toView, 则用这两个view的内容对containerView进行填充, 即可实现转场细节了.

本文的Demo中实现了几种常见的转场动画, 包括present/dismiss, presentHalf, Bubble, Drawer,push/pop.

UINavigationControllerDelegate

在UINavigationController的转场中, 要指定UINavigationControllerDelegate对象.

self.navigationController.delegate = self;
[self.navigationController pushViewController:itemVC animated:YES];

push/pop主要是如下两个方法

//              
- (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                   animationControllerForOperation:(UINavigationControllerOperation)operation
                                                fromViewController:(UIViewController *)fromVC
                                                  toViewController:(UIViewController *)toVC;
//            
- (id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
animationController;
interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>)

使用如下:

#pragma mark - <UINavigationControllerDelegate>

- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                            animationControllerForOperation:(UINavigationControllerOperation)operation
                                                         fromViewController:(UIViewController *)fromVC
                                                           toViewController:(UIViewController *)toVC {
    // Push/Pop
    AnimatorPushPopTransition *pushPopTransition = [[AnimatorPushPopTransition alloc] init];

    if (operation == UINavigationControllerOperationPush) {
        pushPopTransition.animatorTransitionType = kAnimatorTransitionTypePush;
    } else {
        pushPopTransition.animatorTransitionType = kAnimatorTransitionTypePop;
    }


    NSArray *indexPaths = [_collectionView indexPathsForSelectedItems];
    if (indexPaths.count == 0) {
        return nil;
    }

    NSIndexPath *selectedIndexPath = indexPaths[0];
    UICollectionViewCell *cell = [_collectionView cellForItemAtIndexPath:selectedIndexPath];

    // 一定要加上convertPoint:toView:操作
    pushPopTransition.itemCenter = [_collectionView convertPoint:cell.center toView:self.view];
    pushPopTransition.itemSize = cell.frame.size;
    pushPopTransition.imageName = [NSString stringWithFormat:@"%ld", (long)selectedIndexPath.item];

    return pushPopTransition;
}

UITabBarController

在UITabBarController的转场中, 同样指定UITabBarControllerDelegate对象即可.

//              
- (id <UIViewControllerAnimatedTransitioning>)tabBarController:(UITabBarController *)tabBarController
            animationControllerForTransitionFromViewController:(UIViewController *)fromVC
                                              toViewController:(UIViewController *)toVC;
//            
- (id <UIViewControllerInteractiveTransitioning>)tabBarController:(UITabBarController *)tabBarController
                      interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>)animationController;

使用情况都比较类似, 这里就不多说了.

Demo

本文的Demo地址:
iOS-TransitionAnimation

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

推荐阅读更多精彩内容