概述
這篇文章,我將講述幾種轉(zhuǎn)場(chǎng)動(dòng)畫的自定義方式,并且每種方式附上一個(gè)示例,畢竟代碼才是我們的語(yǔ)言,這樣比較容易上手。其中主要有以下三種自定義方法,供大家參考:
Push & Pop
Modal
Segue
前兩種大家都很熟悉,第三種是Stroyboard中的拖線,屬于UIStoryboardSegue類,通過(guò)繼承這個(gè)類來(lái)自定義轉(zhuǎn)場(chǎng)過(guò)程動(dòng)畫。
Push & Pop
首先說(shuō)一下Push & Pop這種轉(zhuǎn)場(chǎng)的自定義,操作步驟如下:
創(chuàng)建一個(gè)文件繼承自NSObject, 并遵守UIViewControllerAnimatedTransitioning協(xié)議。
實(shí)現(xiàn)該協(xié)議的兩個(gè)基本方法:
//指定轉(zhuǎn)場(chǎng)動(dòng)畫持續(xù)的時(shí)長(zhǎng)functransitionDuration(transitionContext: UIViewControllerContextTransitioning)->NSTimeInterval//轉(zhuǎn)場(chǎng)動(dòng)畫的具體內(nèi)容funcanimateTransition(transitionContext: UIViewControllerContextTransitioning)
遵守UINavigationControllerDelegate協(xié)議,并實(shí)現(xiàn)此方法:
funcnavigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController)->UIViewControllerAnimatedTransitioning?
在此方法中指定所用的UIViewControllerAnimatedTransitioning,即返回第1步中創(chuàng)建的類。
注意:由于需要Push和Pop,所以需要兩套動(dòng)畫方案。解決方法為:
在第1步中,創(chuàng)建兩個(gè)文件,一個(gè)用于Push動(dòng)畫,一個(gè)用于Pop動(dòng)畫,然后第3步中在返回動(dòng)畫類之前,先判斷動(dòng)畫方式(Push 或 Pop), 使用operation == UINavigationControllerOperation.Push即可判斷,最后根據(jù)不同的方式返回不同的類。
到這里就可以看到轉(zhuǎn)場(chǎng)動(dòng)畫的效果了,但是大家都知道,系統(tǒng)默認(rèn)的Push 和 Pop動(dòng)畫都支持手勢(shì)驅(qū)動(dòng),并且可以根據(jù)手勢(shì)移動(dòng)距離改變動(dòng)畫完成度。幸運(yùn)的是,Cocoa 已經(jīng)集成了相關(guān)方法,我們只用告訴它百分比就可以了。所以下一步就是手勢(shì)驅(qū)動(dòng)。
在第二個(gè)UIViewController中給View添加一個(gè)滑動(dòng)(Pan)手勢(shì)。
創(chuàng)建一個(gè)UIPercentDrivenInteractiveTransition屬性。
在手勢(shì)的監(jiān)聽方法中計(jì)算手勢(shì)移動(dòng)的百分比,并使用UIPercentDrivenInteractiveTransition屬性的updateInteractiveTransition()方法實(shí)時(shí)更新百分比。
最后在手勢(shì)的state為ended或cancelled時(shí),根據(jù)手勢(shì)完成度決定是還原動(dòng)畫還是結(jié)束動(dòng)畫,使用UIPercentDrivenInteractiveTransition屬性的cancelInteractiveTransition()或finishInteractiveTransition()方法。
實(shí)現(xiàn)UINavigationControllerDelegate中的另一個(gè)返回UIViewControllerInteractiveTransitioning的方法,并在其中返回第4步創(chuàng)建的UIPercentDrivenInteractiveTransition屬性。
至此,Push 和 Pop 方式的自定義就完成了,具體細(xì)節(jié)看下面的示例。
自定義 Push & Pop 示例
此示例來(lái)自Kitten Yang的blog實(shí)現(xiàn)Keynote中的神奇移動(dòng)效果,我將其用Swift實(shí)現(xiàn)了一遍,源代碼地址:MagicMove,下面是運(yùn)行效果。

MagicMove.gif
初始化
創(chuàng)建兩個(gè)ViewController,一個(gè)繼承自UICollectionViewController,取名ViewController。另一個(gè)繼承UIViewController,取名DetailViewController。在Stroyboard中創(chuàng)建并綁定。
在Stroyboard中拖一個(gè)UINavigationController,刪去默認(rèn)的 rootViewController,使ViewController作為其 rootViewController,再拖一條從ViewController到DetailViewController的 segue。
在ViewController中自定義UICollectionViewCell,添加UIImageView和UILabel。
在DetailViewController中添加UIImageView和UITextView

mm_inital.png
添加UIViewControllerAnimatedTransitioning
添加一個(gè)Cocoa Touch Class,繼承自NSObject,取名MagicMoveTransion,遵守UIViewControllerAnimatedTransitioning協(xié)議。
實(shí)現(xiàn)協(xié)議的兩個(gè)方法,并在其中編寫Push的動(dòng)畫。具體的動(dòng)畫實(shí)現(xiàn)過(guò)程都在代碼的注釋里 :
functransitionDuration(transitionContext: UIViewControllerContextTransitioning)->NSTimeInterval{return0.5}funcanimateTransition(transitionContext: UIViewControllerContextTransitioning){//1.獲取動(dòng)畫的源控制器和目標(biāo)控制器letfromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)as!ViewControllerlettoVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)as!DetailViewControllerletcontainer = transitionContext.containerView()//2.創(chuàng)建一個(gè) Cell 中 imageView 的截圖,并把 imageView 隱藏,造成使用戶以為移動(dòng)的就是 imageView 的假象letsnapshotView = fromVC.selectedCell.imageView.snapshotViewAfterScreenUpdates(false)? ? snapshotView.frame = container.convertRect(fromVC.selectedCell.imageView.frame, fromView: fromVC.selectedCell)? ? fromVC.selectedCell.imageView.hidden =true//3.設(shè)置目標(biāo)控制器的位置,并把透明度設(shè)為0,在后面的動(dòng)畫中慢慢顯示出來(lái)變?yōu)?toVC.view.frame = transitionContext.finalFrameForViewController(toVC)? ? toVC.view.alpha =0//4.都添加到 container 中。注意順序不能錯(cuò)了container.addSubview(toVC.view)? ? container.addSubview(snapshotView)//5.執(zhí)行動(dòng)畫UIView.animateWithDuration(transitionDuration(transitionContext), delay:0, options:UIViewAnimationOptions.CurveEaseInOut, animations: { () ->VoidinsnapshotView.frame = toVC.avatarImageView.frame? ? ? ? ? ? toVC.view.alpha =1}) { (finish:Bool) ->VoidinfromVC.selectedCell.imageView.hidden =falsetoVC.avatarImageView.image = toVC.image? ? ? ? ? ? snapshotView.removeFromSuperview()//一定要記得動(dòng)畫完成后執(zhí)行此方法,讓系統(tǒng)管理 navigationtransitionContext.completeTransition(true)? ? }}
使用動(dòng)畫
讓ViewController遵守UINavigationControllerDelegate協(xié)議。
在ViewController中設(shè)置NavigationController的代理為自己:
overridefuncviewDidAppear(animated: Bool){super.viewDidAppear(animated)self.navigationController?.delegate =self}
實(shí)現(xiàn)UINavigationControllerDelegate協(xié)議方法:
funcnavigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController)->UIViewControllerAnimatedTransitioning? {ifoperation ==UINavigationControllerOperation.Push{returnMagicMoveTransion()? ? }else{returnnil}}
在ViewController的controllerCell的點(diǎn)擊方法中,發(fā)送segue
overridefunccollectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){self.selectedCell = collectionView.cellForItemAtIndexPath(indexPath)as!MMCollectionViewCellself.performSegueWithIdentifier("detail", sender:nil)}
在發(fā)送segue的時(shí)候,把點(diǎn)擊的image發(fā)送給DetailViewController
overridefuncprepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){ifsegue.identifier =="detail"{letdetailVC = segue.destinationViewControlleras!DetailViewControllerdetailVC.image =self.selectedCell.imageView.image? ? }}
至此,在點(diǎn)擊 Cell 后,就會(huì)執(zhí)行剛剛自定義的動(dòng)畫了。接下來(lái)就要加入手勢(shì)驅(qū)動(dòng)。
手勢(shì)驅(qū)動(dòng)
在DetailViewController的ViewDidAppear()方法中,加入滑動(dòng)手勢(shì)。
letedgePan =UIScreenEdgePanGestureRecognizer(target:self, action:Selector("edgePanGesture:"))? ? edgePan.edges =UIRectEdge.Leftself.view.addGestureRecognizer(edgePan)
在手勢(shì)監(jiān)聽方法中,創(chuàng)建UIPercentDrivenInteractiveTransition屬性,并實(shí)現(xiàn)手勢(shì)百分比更新。
funcedgePanGesture(edgePan: UIScreenEdgePanGestureRecognizer){letprogress = edgePan.translationInView(self.view).x /self.view.bounds.widthifedgePan.state ==UIGestureRecognizerState.Began{self.percentDrivenTransition =UIPercentDrivenInteractiveTransition()self.navigationController?.popViewControllerAnimated(true)? ? }elseifedgePan.state ==UIGestureRecognizerState.Changed{self.percentDrivenTransition?.updateInteractiveTransition(progress)? ? }elseifedgePan.state ==UIGestureRecognizerState.Cancelled|| edgePan.state ==UIGestureRecognizerState.Ended{ifprogress >0.5{self.percentDrivenTransition?.finishInteractiveTransition()? ? ? ? }else{self.percentDrivenTransition?.cancelInteractiveTransition()? ? ? ? }self.percentDrivenTransition =nil}}
實(shí)現(xiàn)返回UIViewControllerInteractiveTransitioning的方法并返回剛剛創(chuàng)建的UIPercentDrivenInteractiveTransition屬性。
funcnavigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning)->UIViewControllerInteractiveTransitioning? {ifanimationControllerisMagicMovePopTransion{returnself.percentDrivenTransition? ? }else{returnnil}}
OK,到現(xiàn)在,手勢(shì)驅(qū)動(dòng)就寫好了,但是還不能使用,因?yàn)檫€沒(méi)有實(shí)現(xiàn) Pop 方法!現(xiàn)在自己去實(shí)現(xiàn) Pop 動(dòng)畫吧!請(qǐng)參考源代碼:MagicMove
Modal
modal轉(zhuǎn)場(chǎng)方式即使用presentViewController()方法推出的方式,默認(rèn)情況下,第二個(gè)視圖從屏幕下方彈出。下面就來(lái)介紹下 modal 方式轉(zhuǎn)場(chǎng)動(dòng)畫的自定義。
創(chuàng)建一個(gè)文件繼承自NSObject, 并遵守UIViewControllerAnimatedTransitioning協(xié)議。
實(shí)現(xiàn)該協(xié)議的兩個(gè)基本方法:
//指定轉(zhuǎn)場(chǎng)動(dòng)畫持續(xù)的時(shí)長(zhǎng)functransitionDuration(transitionContext: UIViewControllerContextTransitioning)->NSTimeInterval//轉(zhuǎn)場(chǎng)動(dòng)畫的具體內(nèi)容funcanimateTransition(transitionContext: UIViewControllerContextTransitioning)
以上兩個(gè)步驟和Push & Pop的自定義一樣,接下來(lái)就是不同的。
如果使用Modal方式從一個(gè) VC 到另一個(gè) VC,那么需要第一個(gè) VC 遵循UIViewControllerTransitioningDelegate協(xié)議,并實(shí)現(xiàn)以下兩個(gè)協(xié)議方法:
//present動(dòng)畫optionalfuncanimationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController)->UIViewControllerAnimatedTransitioning?//dismiss動(dòng)畫optionalfuncanimationControllerForDismissedController(dismissed: UIViewController)->UIViewControllerAnimatedTransitioning?
在第一個(gè) VC 的prepareForSegue()方法中,指定第二個(gè) VC 的transitioningDelegate為 self。
由第3步中兩個(gè)方法就可以知道,在創(chuàng)建轉(zhuǎn)場(chǎng)動(dòng)畫時(shí),最好也創(chuàng)建兩個(gè)動(dòng)畫類,一個(gè)用于Present, 一個(gè)用于Dismiss,如果只創(chuàng)建一個(gè)動(dòng)畫類,就需要在實(shí)現(xiàn)動(dòng)畫的時(shí)候判斷是Present還是Dismiss。
這時(shí),轉(zhuǎn)場(chǎng)動(dòng)畫就可以實(shí)現(xiàn)了,接下來(lái)就手勢(shì)驅(qū)動(dòng)了
在第一個(gè) VC 中創(chuàng)建一個(gè)UIPercentDrivenInteractiveTransition屬性,并且在prepareForSegue()方法中為第二個(gè) VC.view 添加一個(gè)手勢(shì),用以 dismiss. 在手勢(shì)的監(jiān)聽方法中處理方式和Push & Pop相同。
實(shí)現(xiàn)UIViewControllerTransitioningDelegate協(xié)議的另外兩個(gè)方法,分別返回Present和Dismiss動(dòng)畫的百分比。
//百分比PushfuncinteractionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning)->UIViewControllerInteractiveTransitioning? {returnself.percentDrivenTransition }//百分比PopfuncinteractionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning)->UIViewControllerInteractiveTransitioning? {returnself.percentDrivenTransition }
至此,Modal方式的自定義轉(zhuǎn)場(chǎng)動(dòng)畫就寫完了。自己在編碼的時(shí)候有一些小細(xì)節(jié)需要注意,下面將展示使用Modal方式的自定義動(dòng)畫的示例。
自定義 Modal 示例
此示例和上面一個(gè)示例一樣,來(lái)自Kitten Yang的blog實(shí)現(xiàn)3D翻轉(zhuǎn)效果,我也將其用Swift實(shí)現(xiàn)了一遍,同樣我的源代碼地址:FlipTransion,運(yùn)行效果如下:

FlipTransion.gif
初始化
創(chuàng)建兩個(gè)UIViewController, 分別命名為:FirstViewController和SecondViewController。并在Storyboard中添加兩個(gè)UIViewController并綁定。
分別給兩個(gè)視圖添加兩個(gè)UIImageView,這樣做的目的是為了區(qū)分兩個(gè)控制器。當(dāng)然你也可以給兩個(gè)控制器設(shè)置不同的背景,總之你開心就好。但是,既然做,就做認(rèn)真點(diǎn)唄。注意:如果使用圖片并設(shè)置為Aspect Fill或者其他的 Fill,一定記得調(diào)用imageView的clipsToBounds()方法裁剪去多余的部分。
分別給兩個(gè)控制器添加兩個(gè)按鈕,第一個(gè)按鈕拖線到第二個(gè)控制器,第二個(gè)控制器綁定一個(gè)方法用來(lái)dismiss。

ft_inital.png
添加UIViewControllerAnimatedTransitioning
添加一個(gè)Cocoa Touch Class,繼承自NSObject,取名BWFlipTransionPush(名字嘛,你開心就好。),遵守UIViewControllerAnimatedTransitioning協(xié)議。
實(shí)現(xiàn)協(xié)議的兩個(gè)方法,并在其中編寫Push的動(dòng)畫。具體的動(dòng)畫實(shí)現(xiàn)過(guò)程都在代碼的注釋里 :
funcanimateTransition(transitionContext: UIViewControllerContextTransitioning){letfromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)as!FirstViewControllerlettoVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)as!SecondViewControllerletcontainer = transitionContext.containerView()? ? container.addSubview(toVC.view)? ? container.bringSubviewToFront(fromVC.view)//改變m34vartransfrom =CATransform3DIdentitytransfrom.m34 = -0.002container.layer.sublayerTransform = transfrom//設(shè)置anrchPoint 和 positionletinitalFrame = transitionContext.initialFrameForViewController(fromVC)? ? toVC.view.frame = initalFrame? ? fromVC.view.frame = initalFrame? ? fromVC.view.layer.anchorPoint =CGPointMake(0,0.5)? ? fromVC.view.layer.position =CGPointMake(0, initalFrame.height /2.0)//添加陰影效果letshadowLayer =CAGradientLayer()? ? shadowLayer.colors = [UIColor(white:0, alpha:1).CGColor,UIColor(white:0, alpha:0.5).CGColor,UIColor(white:1, alpha:0.5)]? ? shadowLayer.startPoint =CGPointMake(0,0.5)? ? shadowLayer.endPoint =CGPointMake(1,0.5)? ? shadowLayer.frame = initalFrameletshadow =UIView(frame: initalFrame)? ? shadow.backgroundColor =UIColor.clearColor()? ? shadow.layer.addSublayer(shadowLayer)? ? fromVC.view.addSubview(shadow)? ? shadow.alpha =0//動(dòng)畫UIView.animateWithDuration(transitionDuration(transitionContext), delay:0, options:UIViewAnimationOptions.CurveEaseOut, animations: { () ->VoidinfromVC.view.layer.transform =CATransform3DMakeRotation(CGFloat(-M_PI_2),0,1,0)? ? ? ? ? ? shadow.alpha =1.0}) { (finished:Bool) ->VoidinfromVC.view.layer.anchorPoint =CGPointMake(0.5,0.5)? ? ? ? ? ? fromVC.view.layer.position =CGPointMake(CGRectGetMidX(initalFrame),CGRectGetMidY(initalFrame))? ? ? ? ? ? fromVC.view.layer.transform =CATransform3DIdentityshadow.removeFromSuperview()? ? ? ? ? ? transitionContext.completeTransition(!transitionContext.transitionWasCancelled())? ? }}
動(dòng)畫的過(guò)程我就不多說(shuō)了,仔細(xì)看就會(huì)明白。
使用動(dòng)畫
讓FirstViewController遵守UIViewControllerTransitioningDelegate協(xié)議,并將self.transitioningDelegate設(shè)置為 self。
實(shí)現(xiàn)UIViewControllerTransitioningDelegate協(xié)議的兩個(gè)方法,用來(lái)指定動(dòng)畫類。
//動(dòng)畫PushfuncanimationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController)->UIViewControllerAnimatedTransitioning? {returnBWFlipTransionPush()}//動(dòng)畫PopfuncanimationControllerForDismissedController(dismissed: UIViewController)->UIViewControllerAnimatedTransitioning? {returnBWFlipTransionPop()}
OK,如果你完成了Pop動(dòng)畫,那么現(xiàn)在就可以實(shí)現(xiàn)自定義 Modal 轉(zhuǎn)場(chǎng)了。現(xiàn)在只差手勢(shì)驅(qū)動(dòng)了。
手勢(shì)驅(qū)動(dòng)
想要同時(shí)實(shí)現(xiàn)Push和Pop手勢(shì),就需要給兩個(gè)viewController.view添加手勢(shì)。首先在FirstViewController中給自己添加一個(gè)屏幕右邊的手勢(shì),在prepareForSegue()方法中給SecondViewController.view添加一個(gè)屏幕左邊的手勢(shì),讓它們使用同一個(gè)手勢(shì)監(jiān)聽方法。
實(shí)現(xiàn)監(jiān)聽方法,不多說(shuō),和之前一樣,但還是有仔細(xì)看,因?yàn)楸臼纠修D(zhuǎn)場(chǎng)動(dòng)畫比較特殊,而且有兩個(gè)手勢(shì),所以這里計(jì)算百分比使用的是KeyWindow。同時(shí)不要忘了:UIPercentDrivenInteractiveTransition屬性。
funcedgePanGesture(edgePan: UIScreenEdgePanGestureRecognizer){letprogress =abs(edgePan.translationInView(UIApplication.sharedApplication().keyWindow!).x) /UIApplication.sharedApplication().keyWindow!.bounds.widthifedgePan.state ==UIGestureRecognizerState.Began{self.percentDrivenTransition =UIPercentDrivenInteractiveTransition()ifedgePan.edges ==UIRectEdge.Right{self.performSegueWithIdentifier("present", sender:nil)? ? ? ? }elseifedgePan.edges ==UIRectEdge.Left{self.dismissViewControllerAnimated(true, completion:nil)? ? ? ? }? ? }elseifedgePan.state ==UIGestureRecognizerState.Changed{self.percentDrivenTransition?.updateInteractiveTransition(progress)? ? }elseifedgePan.state ==UIGestureRecognizerState.Cancelled|| edgePan.state ==UIGestureRecognizerState.Ended{ifprogress >0.5{self.percentDrivenTransition?.finishInteractiveTransition()? ? ? ? }else{self.percentDrivenTransition?.cancelInteractiveTransition()? ? ? ? }self.percentDrivenTransition =nil}}
實(shí)現(xiàn)UIViewControllerTransitioningDelegate協(xié)議的另外兩個(gè)方法,分別返回Present和Dismiss動(dòng)畫的百分比。
//百分比PushfuncinteractionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning)->UIViewControllerInteractiveTransitioning? {returnself.percentDrivenTransition}//百分比PopfuncinteractionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning)->UIViewControllerInteractiveTransitioning? {returnself.percentDrivenTransition}
現(xiàn)在,基于Modal的自定義轉(zhuǎn)場(chǎng)動(dòng)畫示例就完成了。獲取完整源代碼:FlipTransion
Segue
這種方法比較特殊,是將Stroyboard中的拖線與自定義的UIStoryboardSegue類綁定自實(shí)現(xiàn)定義轉(zhuǎn)場(chǎng)過(guò)程動(dòng)畫。
首先我們來(lái)看看UIStoryboardSegue是什么樣的。
@availability(iOS, introduced=5.0)classUIStoryboardSegue:NSObject{// Convenience constructor for returning a segue that performs a handler block in its -perform method.@availability(iOS, introduced=6.0)? ? convenienceinit(identifier:String?, source:UIViewController, destination:UIViewController, performHandler: () ->Void)init!(identifier:String?, source:UIViewController, destination:UIViewController)// Designated initializervaridentifier:String? {get}varsourceViewController:AnyObject{get}vardestinationViewController:AnyObject{get}funcperform()}
以上是UIStoryboardSegue類的定義。從中可以看出,只有一個(gè)方法perform(),所以很明顯,就是重寫這個(gè)方法來(lái)自定義轉(zhuǎn)場(chǎng)動(dòng)畫。
再注意它的其他屬性:sourceViewController和destinationViewController,通過(guò)這兩個(gè)屬性,我們就可以訪問(wèn)一個(gè)轉(zhuǎn)場(chǎng)動(dòng)畫中的兩個(gè)主角了,于是自定義動(dòng)畫就可以隨心所欲了。
只有一點(diǎn)需要注意:在拖線的時(shí)候,注意在彈出的選項(xiàng)中選擇custom。然后就可以和自定義的UIStoryboardSegue綁定了。
那么,問(wèn)題來(lái)了,這里只有perform,那 返回時(shí)的動(dòng)畫怎么辦呢?請(qǐng)往下看:
Dismiss
由于perfrom的方法叫做:segue,那么返回轉(zhuǎn)場(chǎng)的上一個(gè)控制器叫做:unwind segue
解除轉(zhuǎn)場(chǎng)(unwind segue)通常和正常自定義轉(zhuǎn)場(chǎng)(segue)一起出現(xiàn)。
要解除轉(zhuǎn)場(chǎng)起作用,我們必須重寫perform方法,并應(yīng)用自定義動(dòng)畫。另外,導(dǎo)航返回源視圖控制器的過(guò)渡效果不需要和對(duì)應(yīng)的正常轉(zhuǎn)場(chǎng)相同。
其實(shí)現(xiàn)步驟為:
創(chuàng)建一個(gè)IBAction方法,該方法在解除轉(zhuǎn)場(chǎng)被執(zhí)行的時(shí)候會(huì)選擇地執(zhí)行一些代碼。這個(gè)方法可以有你想要的任何名字,而且不強(qiáng)制包含其它東西。它需要定義,但可以留空,解除轉(zhuǎn)場(chǎng)的定義需要依賴這個(gè)方法。
解除轉(zhuǎn)場(chǎng)的創(chuàng)建,設(shè)置的配置。這和之前的轉(zhuǎn)場(chǎng)創(chuàng)建不太一樣,等下我們將看看這個(gè)是怎么實(shí)現(xiàn)的。
通過(guò)重寫UIStoryboardSegue子類里的perform()方法,來(lái)實(shí)現(xiàn)自定義動(dòng)畫。
UIViewController類提供了特定方法的定義,所以系統(tǒng)知道解除轉(zhuǎn)場(chǎng)即將執(zhí)行。
當(dāng)然,這么說(shuō)有一些讓人琢磨不透,不知道什么意思。那么,下面再通過(guò)一個(gè)示例來(lái)深入了解一下。
Segue 示例
這個(gè)示例是我自己寫的,源代碼地址:SegueTransion,開門見(jiàn)山,直接上圖。
GIF演示

SegueTransion.gif
初始化
創(chuàng)建兩個(gè)UIViewController, 分別命名為:FirstViewController和SecondViewController。并在Storyboard中添加兩個(gè)UIViewController并綁定。
分別給兩個(gè)控制器添加背景圖片或使用不同的背景色,用以區(qū)分。在FirstViewController中添加一個(gè)觸發(fā)按鈕,并拖線到SecondViewController中,在彈出的選項(xiàng)中選擇custion。

st_inital.png
Present
添加一個(gè)Cocoa Touch Class,繼承自UIStoryboardSegue,取名FirstSegue(名字請(qǐng)隨意)。并將其綁定到上一步中拖拽的segue上。
重寫FirstSegue中的perform()方法,在其中編寫動(dòng)畫邏輯。
overridefuncperform(){varfirstVCView =self.sourceViewController.viewasUIView!varsecondVCView =self.destinationViewController.viewasUIView!letscreenWidth =UIScreen.mainScreen().bounds.size.widthletscreenHeight =UIScreen.mainScreen().bounds.size.height? ? ? secondVCView.frame =CGRectMake(0.0, screenHeight, screenWidth, screenHeight)letwindow =UIApplication.sharedApplication().keyWindow? ? ? window?.insertSubview(secondVCView, aboveSubview: firstVCView)UIView.animateWithDuration(0.5, delay:0, usingSpringWithDamping:0.5, initialSpringVelocity:0, options:UIViewAnimationOptions.CurveLinear, animations: { () ->VoidinsecondVCView.frame =CGRectOffset(secondVCView.frame,0.0, -screenHeight)? ? ? ? ? }) { (finished:Bool) ->Voidinself.sourceViewController.presentViewController(self.destinationViewControlleras!UIViewController,? ? ? ? ? ? ? ? ? animated:false,? ? ? ? ? ? ? ? ? completion:nil)? ? ? }? }
還是一樣,動(dòng)畫的過(guò)程自己看,都是很簡(jiǎn)單的。
Present手勢(shì)
這里需要注意,使用這種方式自定義的轉(zhuǎn)場(chǎng)動(dòng)畫不能動(dòng)態(tài)手勢(shì)驅(qū)動(dòng),也就是說(shuō)不能根據(jù)手勢(shì)百分比動(dòng)態(tài)改變動(dòng)畫完成度。
所以,這里只是簡(jiǎn)單的添加一個(gè)滑動(dòng)手勢(shì)(swip)。
在FisrtViewController中添加手勢(shì):
varswipeGestureRecognizer:UISwipeGestureRecognizer=UISwipeGestureRecognizer(target:self, action:"showSecondViewController")? swipeGestureRecognizer.direction =UISwipeGestureRecognizerDirection.Upself.view.addGestureRecognizer(swipeGestureRecognizer)
實(shí)現(xiàn)手勢(shì)監(jiān)聽方法:
funcshowSecondViewController(){self.performSegueWithIdentifier("idFirstSegue", sender:self)}
現(xiàn)在已經(jīng)可以present了,接下來(lái)實(shí)現(xiàn)dismiss。
Dismiss
在FirstViewController中添加一個(gè)IBAction方法,方法名可以隨便,有沒(méi)有返回值都隨便。
在Storyboard中選擇SecondViewController按住control鍵拖線到SecondViewController的Exit圖標(biāo)。并在彈出選項(xiàng)中選擇上一步添加IBAction的方法。

st_unwind.png
在Storyboard左側(cè)的文檔視圖中找到上一步拖的segue,并設(shè)置identifier

st_unwindSegue.png
再添加一個(gè)Cocoa Touch Class,繼承自UIStoryboardSegue,取名FirstSegueUnWind(名字請(qǐng)隨意)。并重寫其perform()方法,用來(lái)實(shí)現(xiàn)dismiss動(dòng)畫。
在FirstViewController中重寫下面方法。并根據(jù)identifier判斷是不是需要 dismiss,如果是就返回剛剛創(chuàng)建的FirstUnWindSegue。
overridefuncsegueForUnwindingToViewController(toViewController: UIViewController, fromViewController: UIViewController, identifier: String?)->UIStoryboardSegue{ifidentifier =="firstSegueUnwind"{returnFirstUnwindSegue(identifier: identifier, source: fromViewController, destination: toViewController, performHandler: { () ->Voidin})? ? }returnsuper.segueForUnwindingToViewController(toViewController, fromViewController: fromViewController, identifier: identifier)}
最后一步,在SecondViewController的按鈕的監(jiān)聽方法中實(shí)現(xiàn) dismiss,注意不是調(diào)用self.dismiss...!
@IBActionfuncshouldDismiss(sender: AnyObject){self.performSegueWithIdentifier("firstSegueUnwind", sender:self)? }
給SecondViewController添加手勢(shì),將手勢(shì)監(jiān)聽方法也設(shè)置為以上這個(gè)方法, 參考代碼:SegueTransion。
總結(jié)
一張圖總結(jié)一下3種方法的異同點(diǎn)。

總結(jié).png
到這里,終于吧3中方法的自定義都寫完了,寫這篇 blog 花了我一天的時(shí)間!希望我自己和看過(guò)的同學(xué)都能記??!同時(shí),有錯(cuò)誤的地方歡迎提出。
文/伯恩的遺產(chǎn)(簡(jiǎn)書作者)
原文鏈接:http://www.itdecent.cn/p/38cd35968864#
著作權(quán)歸作者所有,轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),并標(biāo)注“簡(jiǎn)書作者”。