一張圖看懂 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閱讀 228,983評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,772評論 3 422
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,947評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,201評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,960評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,350評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,406評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,549評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,104評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,914評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,089評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,647評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,340評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,753評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,007評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,834評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,106評論 2 375

推薦閱讀更多精彩內容