关于自己定义转场动画,我都告诉你。
概述
这篇文章,我将讲述几种转场动画的自己定义方式。而且每种方式附上一个演示样例。毕竟代码才是我们的语言。这样比較easy上手。当中主要有下面三种自己定义方法,供大家參考:
- Push & Pop
- Modal
- Segue
前两种大家都非常熟悉,第三种是 Stroyboard 中的拖线,属于 UIStoryboardSegue 类,通过继承这个类来自己定义转场过程动画。
Push & Pop
首先说一下 Push & Pop 这样的转场的自己定义。操作过程例如以下:
- 创建一个文件继承自
NSObject, 并遵守UIViewControllerAnimatedTransitioning协议。 - 实现该协议的两个基本方法:
1234//指定转场动画持续的时长func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval//转场动画的详细内容func animateTransition(transitionContext: UIViewControllerContextTransitioning) - 遵守
UINavigationControllerDelegate协议,并实现此方法:
1func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?在此方法中指定所用的
UIViewControllerAnimatedTransitioning,即返回 第1步 中创建的类。注意:因为须要Push和Pop。所以须要两套动画方案。解决方法为:
在 第1步 中。创建两个文件。一个用于
Push动画,一个用于Pop动画。然后 第3步 中在返回动画类之前,先推断动画方式(Push 或 Pop), 使用operation == UINavigationControllerOperation.Push就可以推断,最后依据不同的方式返回不同的类。到这里就能够看到转场动画的效果了。可是大家都知道,系统默认的
Push 和 Pop动画都支持手势驱动,而且能够依据手势移动距离改变动画完毕度。幸运的是,Cocoa 已经集成了相关方法。我们仅仅用告诉它百分比就能够了。所下面一步就是 手势驱动。
- 在第二个
UIViewController中给View加入一个滑动(Pan)手势。
创建一个UIPercentDrivenInteractiveTransition属性。
在手势的监听方法中计算手势移动的百分比,并使用UIPercentDrivenInteractiveTransition属性的updateInteractiveTransition()方法实时更新百分比。
最后在手势的state为ended或cancelled时,依据手势完毕度决定是还原动画还是结束动画,使用UIPercentDrivenInteractiveTransition属性的cancelInteractiveTransition()或finishInteractiveTransition()方法。 - 实现
UINavigationControllerDelegate中的还有一个返回UIViewControllerInteractiveTransitioning的方法,并在当中返回第4步创建的UIPercentDrivenInteractiveTransition属性。
至此,Push 和 Pop 方式的自己定义就完毕了。详细细节看以下的演示样例。
自己定义 Push & Pop 演示样例
此演示样例来自 Kitten Yang 的blog 实现Keynote中的奇妙移动效果,我将其用 Swift 实现了一遍,源码地址: MagicMove,以下是执行效果。

初始化
- 创建两个
ViewController,一个继承自UICollectionViewController,取名ViewController。还有一个继承UIViewController,取名DetailViewController。在
Stroyboard中创建并绑定。 - 在
Stroyboard中拖一个UINavigationController。删去默认的 rootViewController,使ViewController作为其 rootViewController。再拖一条从ViewController到DetailViewController的 segue。 - 在
ViewController中自己定义UICollectionViewCell,加入UIImageView和UILabel。 - 在
DetailViewController中加入UIImageView和UITextView

加入 UIViewControllerAnimatedTransitioning
- 加入一个
Cocoa Touch Class。继承自NSObject,取名MagicMoveTransion。遵守UIViewControllerAnimatedTransitioning协议。 - 实现协议的两个方法,并在当中编写
Push的动画。 详细的动画实现过程都在代码的凝视里 :
123456789101112131415161718192021222324252627282930313233343536func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {return 0.5}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {//1.获取动画的源控制器和目标控制器let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewControllerlet toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! DetailViewControllerlet container = transitionContext.containerView()
//2.创建一个 Cell 中 imageView 的截图。并把 imageView 隐藏,造成使用户以为移动的就是 imageView 的假象let snapshotView = fromVC.selectedCell.imageView.snapshotViewAfterScreenUpdates(false)snapshotView.frame = container.convertRect(fromVC.selectedCell.imageView.frame, fromView: fromVC.selectedCell)fromVC.selectedCell.imageView.hidden = true
//3.设置目标控制器的位置,并把透明度设为0,在后面的动画中慢慢显示出来变为1toVC.view.frame = transitionContext.finalFrameForViewController(toVC)toVC.view.alpha = 0
//4.都加入到 container 中。注意顺序不能错了container.addSubview(toVC.view)container.addSubview(snapshotView)
//5.运行动画UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void insnapshotView.frame = toVC.avatarImageView.frametoVC.view.alpha = 1}) { (finish: Bool) -> Void infromVC.selectedCell.imageView.hidden = falsetoVC.avatarImageView.image = toVC.imagesnapshotView.removeFromSuperview()
//一定要记得动画完毕后运行此方法,让系统管理 navigationtransitionContext.completeTransition(true)}}
使用动画
- 让
ViewController遵守UINavigationControllerDelegate协议。 - 在
ViewController中设置NavigationController的代理为自己:
12345override func viewDidAppear(animated: Bool) {super.viewDidAppear(animated)
self.navigationController?.delegate = self} - 实现
UINavigationControllerDelegate协议方法:
1234567func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {if operation == UINavigationControllerOperation.Push {return MagicMoveTransion()} else {return nil}} - 在
ViewController的controllerCell的点击方法中,发送segue
12345override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {self.selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as! MMCollectionViewCell
self.performSegueWithIdentifier("detail", sender: nil)} - 在发送
segue的时候。把点击的image发送给DetailViewController
123456override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {if segue.identifier == "detail" {let detailVC = segue.destinationViewController as! DetailViewControllerdetailVC.image = self.selectedCell.imageView.image}}至此。在点击 Cell 后,就会运行刚刚自己定义的动画了。接下来就要增加手势驱动。
手势驱动
- 在
DetailViewController的ViewDidAppear()方法中。增加滑动手势。
123let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("edgePanGesture:"))edgePan.edges = UIRectEdge.Leftself.view.addGestureRecognizer(edgePan) - 在手势监听方法中。创建
UIPercentDrivenInteractiveTransition属性,并实现手势百分比更新。
1234567891011121314151617func edgePanGesture(edgePan: UIScreenEdgePanGestureRecognizer) {let progress = edgePan.translationInView(self.view).x / self.view.bounds.width
if edgePan.state == UIGestureRecognizerState.Began {self.percentDrivenTransition = UIPercentDrivenInteractiveTransition()self.navigationController?.popViewControllerAnimated(true)
} else if edgePan.state == UIGestureRecognizerState.Changed {self.percentDrivenTransition?.updateInteractiveTransition(progress)} else if edgePan.state == UIGestureRecognizerState.Cancelled || edgePan.state == UIGestureRecognizerState.Ended {if progress > 0.5 {self.percentDrivenTransition?.finishInteractiveTransition()} else {self.percentDrivenTransition?.cancelInteractiveTransition()}self.percentDrivenTransition = nil}} - 实现返回
UIViewControllerInteractiveTransitioning的方法并返回刚刚创建的UIPercentDrivenInteractiveTransition属性。
1234567func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {if animationController is MagicMovePopTransion {return self.percentDrivenTransition} else {return nil}}
OK,到如今。手势驱动就写好了,可是还不能使用,由于还没有实现 Pop 方法!
如今自己去实现 Pop 动画吧!
请參考源码:MagicMove
Modal
modal转场方式即使用 presentViewController() 方法推出的方式,默认情况下。第二个视图从屏幕下方弹出。以下就来介绍下 modal 方式转场动画的自己定义。
- 创建一个文件继承自
NSObject, 并遵守UIViewControllerAnimatedTransitioning协议。 - 实现该协议的两个基本方法:
1234//指定转场动画持续的时长func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval//转场动画的详细内容func animateTransition(transitionContext: UIViewControllerContextTransitioning)以上两个步骤和
Push & Pop的自己定义一样。接下来就是不同的。 - 假设使用
Modal方式从一个 VC 到还有一个 VC,那么须要第一个 VC 遵循UIViewControllerTransitioningDelegate协议。并实现下面两个协议方法:
12345//present动画optional func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?
//dismiss动画optional func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? - 在第一个 VC 的
prepareForSegue()方法中,指定第二个 VC 的transitioningDelegate为 self。
由 第3步 中两个方法就能够知道,在创建转场动画时,最好也创建两个动画类,一个用于 Present。 一个用于 Dismiss。假设仅仅创建一个动画类,就须要在实现动画的时候推断是
Present还是Dismiss。这时。转场动画就能够实现了,接下来就手势驱动了
- 在第一个 VC 中创建一个
UIPercentDrivenInteractiveTransition属性,而且在prepareForSegue()方法中为第二个 VC.view 加入一个手势,用以 dismiss. 在手势的监听方法中处理方式和Push & Pop同样。 - 实现
UIViewControllerTransitioningDelegate协议的另外两个方法,分别返回Present和Dismiss动画的百分比。
12345678//百分比Pushfunc interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?{
return self.percentDrivenTransition}//百分比Popfunc interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {return self.percentDrivenTransition}至此,
Modal方式的自己定义转场动画就写完了。自己在编码的时候有一些小细节须要注意。以下将展示使用Modal方式的自己定义动画的演示样例。
自己定义 Modal 演示样例
此演示样例和上面一个演示样例一样,来自 Kitten Yang 的blog 实现3D翻转效果,我也将其用 Swift 实现了一遍,相同我的源码地址:FlipTransion,执行效果例如以下:

初始化
- 创建两个
UIViewController, 分别命名为:FirstViewController和SecondViewController。并在
Storyboard中加入两个UIViewController并绑定。 - 分别给两个视图加入两个
UIImageView。这样做的目的是为了区分两个控制器。当然你也能够给两个控制器设置不同的背景,总之你开心就好。可是,既然做,就做认真点呗。注意:假设使用图片并设置为Aspect Fill或者其它的 Fill。一定记得调用imageView的clipsToBounds()方法裁剪去多余的部分。 - 分别给两个控制器加入两个button。第一个button拖线到第二个控制器,第二个控制器绑定一个方法用来dismiss。

加入 UIViewControllerAnimatedTransitioning
- 加入一个
Cocoa Touch Class,继承自NSObject,取名BWFlipTransionPush(名字嘛,你开心就好。),遵守UIViewControllerAnimatedTransitioning协议。 - 实现协议的两个方法。并在当中编写
Push的动画。 详细的动画实现过程都在代码的凝视里 :
1234567891011121314151617181920212223242526272829303132333435363738394041424344func animateTransition(transitionContext: UIViewControllerContextTransitioning) {let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! FirstViewControllerlet toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! SecondViewControllerlet container = transitionContext.containerView()container.addSubview(toVC.view)container.bringSubviewToFront(fromVC.view)
//改变m34var transfrom = CATransform3DIdentitytransfrom.m34 = -0.002container.layer.sublayerTransform = transfrom
//设置anrchPoint 和 positionlet initalFrame = transitionContext.initialFrameForViewController(fromVC)toVC.view.frame = initalFramefromVC.view.frame = initalFramefromVC.view.layer.anchorPoint = CGPointMake(0, 0.5)fromVC.view.layer.position = CGPointMake(0, initalFrame.height / 2.0)
//加入阴影效果let shadowLayer = 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 = initalFramelet shadow = UIView(frame: initalFrame)shadow.backgroundColor = UIColor.clearColor()shadow.layer.addSublayer(shadowLayer)fromVC.view.addSubview(shadow)shadow.alpha = 0
//动画UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void infromVC.view.layer.transform = CATransform3DMakeRotation(CGFloat(-M_PI_2), 0, 1, 0)shadow.alpha = 1.0}) { (finished: Bool) -> Void infromVC.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())}}动画的过程我就不多说了,细致看就会明确。
使用动画
- 让
FirstViewController遵守UIViewControllerTransitioningDelegate协议,并将self.transitioningDelegate设置为 self。 - 实现
UIViewControllerTransitioningDelegate协议的两个方法。用来指定动画类。
12345678//动画Pushfunc animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {return BWFlipTransionPush()}//动画Popfunc animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{
return BWFlipTransionPop()}OK。假设你完毕了Pop动画,那么如今就能够实现自己定义 Modal 转场了。
如今仅仅差手势驱动了。
手势驱动
- 想要同一时候实现
Push和Pop手势,就须要给两个viewController.view加入手势。首先在
FirstViewController中给自己加入一个屏幕右边的手势,在prepareForSegue()方法中给SecondViewController.view加入一个屏幕左边的手势,让它们使用同一个手势监听方法。 - 实现监听方法,不多说,和之前一样,但还是有细致看,由于本演示样例中转场动画比較特殊,并且有两个手势,所以这里计算百分比使用的是
KeyWindow。同一时候不要忘了:UIPercentDrivenInteractiveTransition属性。
123456789101112131415161718192021func edgePanGesture(edgePan: UIScreenEdgePanGestureRecognizer) {let progress = abs(edgePan.translationInView(UIApplication.sharedApplication().keyWindow!).x) / UIApplication.sharedApplication().keyWindow!.bounds.width
if edgePan.state == UIGestureRecognizerState.Began {self.percentDrivenTransition = UIPercentDrivenInteractiveTransition()if edgePan.edges == UIRectEdge.Right {self.performSegueWithIdentifier("present", sender: nil)} else if edgePan.edges == UIRectEdge.Left {self.dismissViewControllerAnimated(true, completion: nil)}} else if edgePan.state == UIGestureRecognizerState.Changed {self.percentDrivenTransition?.updateInteractiveTransition(progress)} else if edgePan.state == UIGestureRecognizerState.Cancelled || edgePan.state == UIGestureRecognizerState.Ended {if progress > 0.5 {self.percentDrivenTransition?.finishInteractiveTransition()
} else {self.percentDrivenTransition?.cancelInteractiveTransition()}self.percentDrivenTransition = nil}} - 实现
UIViewControllerTransitioningDelegate协议的另外两个方法,分别返回Present和Dismiss动画的百分比。
12345678//百分比Pushfunc interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {return self.percentDrivenTransition}//百分比Popfunc interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {return self.percentDrivenTransition}
如今,基于 Modal 的自己定义转场动画演示样例就完毕了。获取完整源码:FlipTransion
Segue
这样的方法比較特殊。是将 Stroyboard 中的拖线与自己定义的 UIStoryboardSegue 类绑定自实现定义转场过程动画。
首先我们来看看 UIStoryboardSegue 是什么样的。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@availability(iOS, introduced=5.0)
class UIStoryboardSegue : NSObject {
// Convenience constructor for returning a segue that performs a handler block in its -perform method.
@availability(iOS, introduced=6.0)
convenience init(identifier: String?, source: UIViewController, destination: UIViewController, performHandler: () -> Void)
init!(identifier: String?
, source: UIViewController, destination: UIViewController) // Designated initializer
var identifier: String? { get }
var sourceViewController: AnyObject { get }
var destinationViewController: AnyObject { get }
func perform()
}
|
以上是 UIStoryboardSegue 类的定义。
从中能够看出,仅仅有一个方法 perform()。所以非常明显,就是重写这种方法来自己定义转场动画。
再注意它的其它属性:sourceViewController 和 destinationViewController,通过这两个属性,我们就能够訪问一个转场动画中的两个主角了,于是自己定义动画就能够随心所欲了。
仅仅有一点须要注意:在拖线的时候,注意在弹出的选项中选择 custom。
然后就能够和自己定义的 UIStoryboardSegue 绑定了。
那么,问题来了,这里仅仅有 perform。那 返回时的动画怎么办呢?请往下看:
Dismiss
因为 perfrom 的方法叫做:segue,那么返回转场的上一个控制器叫做: unwind segue
- 解除转场(unwind segue)通常和正常自己定义转场(segue)一起出现。
- 要解除转场起作用,我们必须重写perform方法,并应用自己定义动画。
另外,导航返回源视图控制器的过渡效果不须要和相应的正常转场同样。
其 实现步骤 为:
- 创建一个
IBAction方法。该方法在解除转场被运行的时候会选择地运行一些代码。这种方法能够有你想要的不论什么名字。并且不强制包括其他东西。它须要定义。但能够留空,解除转场的定义须要依赖这种方法。 - 解除转场的创建。设置的配置。这和之前的转场创建不太一样。等下我们将看看这个是怎么实现的。
- 通过重写
UIStoryboardSegue子类里的perform()方法,来实现自己定义动画。 UIViewController类提供了特定方法的定义,所以系统知道解除转场即将运行。
当然。这么说有一些让人琢磨不透,不知道什么意思。那么。以下再通过一个演示样例来深入了解一下。
Segue 演示样例
这个演示样例是我自己写的,源码地址:SegueTransion,开门见山,直接上图。
GIF演示

初始化
- 创建两个
UIViewController, 分别命名为:FirstViewController和SecondViewController。并在
Storyboard中加入两个UIViewController并绑定。 - 分别给两个控制器加入背景图片或使用不同的背景色,用以区分。
在
FirstViewController中加入一个触发button,并拖线到SecondViewController中,在弹出的选项中选择custion。

Present
- 加入一个
Cocoa Touch Class,继承自UIStoryboardSegue,取名FirstSegue(名字请任意)。并将其绑定到上一步中拖拽的segue上。 - 重写
FirstSegue中的perform()方法。在当中编写动画逻辑。
12345678910111213141516171819override func perform() {var firstVCView = self.sourceViewController.view as UIView!var secondVCView = self.destinationViewController.view as UIView!
let screenWidth = UIScreen.mainScreen().bounds.size.widthlet screenHeight = UIScreen.mainScreen().bounds.size.height
secondVCView.frame = CGRectMake(0.0, screenHeight, screenWidth, screenHeight)let window = UIApplication.sharedApplication().keyWindowwindow?.insertSubview(secondVCView, aboveSubview: firstVCView)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void insecondVCView.frame = CGRectOffset(secondVCView.frame, 0.0, -screenHeight)}) { (finished: Bool) -> Void inself.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,animated: false,completion: nil)}}还是一样。动画的过程自己看,都是非常easy的。
Present手势
这里须要注意。使用这样的方式自己定义的转场动画不能动态手势驱动,也就是说不能依据手势百分比动态改变动画完毕度。
所以。这里仅仅是简单的加入一个滑动手势(swip)。
- 在
FisrtViewController中加入手势:
123var swipeGestureRecognizer: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "showSecondViewController")swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Upself.view.addGestureRecognizer(swipeGestureRecognizer) - 实现手势监听方法:
123func showSecondViewController() {self.performSegueWithIdentifier("idFirstSegue", sender: self)}
如今已经能够 present 了。接下来实现 dismiss。
Dismiss
- 在
FirstViewController中加入一个IBAction方法。方法名能够随便,有没有返回值都随便。 - 在
Storyboard中选择SecondViewController按住control键拖线到SecondViewController的Exit图标。并在弹出选项中选择上一步加入IBAction的方法。

- 在
Storyboard左側的文档视图中找到上一步拖的segue。并设置identifier

- 再加入一个
Cocoa Touch Class,继承自UIStoryboardSegue。取名FirstSegueUnWind(名字请任意)。并重写其perform()方法,用来实现dismiss动画。 - 在
FirstViewController中重写以下方法。并依据identifier推断是不是须要 dismiss,假设是就返回刚刚创建的FirstUnWindSegue。
123456789override func segueForUnwindingToViewController(toViewController: UIViewController, fromViewController: UIViewController, identifier: String?) -> UIStoryboardSegue {
if identifier == "firstSegueUnwind" {return FirstUnwindSegue(identifier: identifier, source: fromViewController, destination: toViewController, performHandler: { () -> Void in})}
return super.segueForUnwindingToViewController(toViewController, fromViewController: fromViewController, identifier: identifier)} - 最后一步。在
SecondViewController的button的监听方法中实现 dismiss, 注意不是调用self.dismiss...!
123@IBAction func shouldDismiss(sender: AnyObject) {self.performSegueWithIdentifier("firstSegueUnwind", sender: self)}给
SecondViewController加入手势,将手势监听方法也设置为以上这种方法, 參考代码:SegueTransion。
总结
一张图总结一下3种方法的异同点。

QQ群290551701 聚集非常多互联网精英,技术总监,架构师,项目经理!开源技术研究,欢迎业内人士,大牛及新手有志于从事IT行业人员进入!

浙公网安备 33010602011771号