0)Who is Hero?
其實(shí)我一直都十分鐘意有關(guān)強(qiáng)化UI功能或是做一些過(guò)場(chǎng)動(dòng)畫的開(kāi)源庫(kù),最近在網(wǎng)上出現(xiàn)一款非常火的過(guò)場(chǎng)動(dòng)劃開(kāi)源庫(kù),短短幾天內(nèi)就4000+ Strar,它的名字也十分的好記,就叫 "Hero"。
https://github.com/lkzhao/Hero 本文撰寫前,已知會(huì)作者

0.1)對(duì)此英雄的第一印象
其實(shí)Hero真正吸引我的是他精美的文案,如Hero它是Foucus在兩個(gè)UIViewController之間的UIViewControllerAnimatedTransitioning,也就是兩個(gè)UIViewController切換時(shí)的過(guò)場(chǎng)動(dòng)畫,而以下是它針對(duì)他的功能提供的示意動(dòng)畫:
很簡(jiǎn)潔又一目了然。
1)Hero's Show #1 - Simple Present
咱們廢話不多說(shuō),直接讓各位客官來(lái)看咱英雄大爺最基本的能耐。

這樣的過(guò)場(chǎng)需要幾行程式碼呢?
View Controller 1
blueView.heroID = "blue"
purpleView.heroID = "purple"
greenView.heroID = "green"
/*
Label同理
*/
View Controller 2
isHeroEnabled = true
blueView.heroID = "blue"
purpleView.heroID = "purple"
greenView.heroID = "green"
/*
Label同理
*/
長(zhǎng)話短說(shuō),Hero在兩個(gè)UIViewController切換之間,將前控制器里ID a的物件位置移到后控制器同為ID a的物件位置。而我們將要探討的即是這個(gè)“切換”中間,作者是如何實(shí)作的。
1.2)Present 流程

1.2.1)Hero為Transitioning做準(zhǔn)備
- Hero:UIViewControllerTransitioningDelegate
- animationController:這里它做的事很簡(jiǎn)單就是把來(lái)源VC與目標(biāo)VC做保存的動(dòng)作,以便日后取用。
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
self.fromViewController = fromViewController ?? presenting
self.toViewController = toViewController ?? presented
return self
}
- interactionControllerForPresentation:這個(gè)方法若不是回傳Null則需自己實(shí)作UIViewControllerInteractiveTransitioning處理相關(guān)參數(shù),若是Null則代表非InterActiveTransition。
InterActiveTransition:最經(jīng)典例子在有NavigationController的情況下手指從熒幕最左端往右滑動(dòng),可以看到上層VC,在還沒(méi)完全放開(kāi)的期間還可以左右滑動(dòng),甚至能放回去不做POP。
- Hero: UIViewControllerAnimatedTransitioning
-
animateTransition:
這個(gè)部分可以說(shuō)是整個(gè)Hero的起源,也是在做VC的過(guò)場(chǎng)動(dòng)畫時(shí),一定會(huì)做到的部分。為了明確表達(dá)這支function,本篇只先提到Context,其余將在第二篇續(xù)談。
-
animateTransition:
public func animateTransition(using context: UIViewControllerContextTransitioning) {
//transitionContext 會(huì)在 end 釋放
if transitionContext != nil {
return
}
transitionContext = context
/*
略
.
*/
}
在官方文檔里明確地提到不建議實(shí)作此類別,以免破壞原本系統(tǒng)自己傳遞的Context。Hero也只是單純將其記下來(lái)。
UIViewControllerContextTransitioning:若要用一個(gè)詞來(lái)概括它, 應(yīng)該就是『上下文』吧,就好像Transition是介于兩個(gè)句子(VC)間的逗點(diǎn),而Context即記錄了上下兩句的語(yǔ)意。里面記錄了與此過(guò)場(chǎng)相關(guān)的控制器、畫面(view)、以及如何過(guò)場(chǎng)(style)