概述

这篇文章,我将讲述几种转场动画的自定义方式,并且每种方式附上一个示例,毕竟代码才是我们的语言,这样比较容易上手。其中主要有以下三种自定义方法,供大家参考:

  • Push & Pop
  • Modal
  • Segue

前两种大家都很熟悉,第三种是 Stroyboard 中的拖线,属于 UIStoryboardSegue 类,通过继承这个类来自定义转场过程动画。

Push & Pop

首先说一下 Push & Pop 这种转场的自定义,操作步骤如下:

创建一个文件继承自 NSObject, 并遵守 UIViewControllerAnimatedTransitioning协议。

实现该协议的两个基本方法:

//指定转场动画持续的时长

func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval      

//转场动画的具体内容      

func animateTransition(transitionContext: UIViewControllerContextTransitioning)

遵守 UINavigationControllerDelegate 协议,并实现此方法:

 func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?

中创建的类。

注意:由于需要 Push 和 Pop,所以需要两套动画方案。解决方法为:

在 第1步 中,创建两个文件,一个用于 Push 动画,一个用于 Pop动画,然后 第3步 中在返回动画类之前,先判断动画方式(Push 或 Pop), 使用 operation == UINavigationControllerOperation.Push 即可判断,最后根据不同的方式返回不同的类。

到这里就可以看到转场动画的效果了,但是大家都知道,系统默认的 Push 和 Pop 动画都支持手势驱动,并且可以根据手势移动距离改变动画完成度。幸运的是,Cocoa 已经集成了相关方法,我们只用告诉它百分比就可以了。所以下一步就是 手势驱动。

创建一个 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


ios 自定义动画 iphone 自定义动作_iOS

添加 UIViewControllerAnimatedTransitioning

  • 添加一个 Cocoa Touch Class,继承自 NSObject,取名 MagicMoveTransion,遵守 UIViewControllerAnimatedTransitioning 协议。
  • 实现协议的两个方法,并在其中编写 Push 的动画。 具体的动画实现过程都在代码的注释里 :

func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
    return 0.5
}
 
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
    //1.获取动画的源控制器和目标控制器
    let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController
    let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! DetailViewController
    let 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,在后面的动画中慢慢显示出来变为1
    toVC.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 in
            snapshotView.frame = toVC.avatarImageView.frame
            toVC.view.alpha = 1
        }) { (finish: Bool) -> Void in
            fromVC.selectedCell.imageView.hidden = false
            toVC.avatarImageView.image = toVC.image
            snapshotView.removeFromSuperview()
 
            //一定要记得动画完成后执行此方法,让系统管理 navigation
            transitionContext.completeTransition(true)    }
}

使用动画

    •  让 ViewController 遵守 UINavigationControllerDelegate 协议。
    •  在 ViewController 中设置 NavigationController 的代理为自己:
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
     
        self.navigationController?.delegate = self
    }
    
    •  实现 UINavigationControllerDelegate 协议方法:
    func 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
     
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        self.selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as! MMCollectionViewCell
     
        self.performSegueWithIdentifier("detail", sender: nil)
    }
     
     在发送 segue 的时候,把点击的 image 发送给 DetailViewController
     
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "detail" {
            let detailVC = segue.destinationViewController as! DetailViewController
            detailVC.image = self.selectedCell.imageView.image
        }
    }
     
     至此,在点击 Cell 后,就会执行刚刚自定义的动画了。接下来就要加入手势驱动。
     
    手势驱动
     
    •  在 DetailViewController 的 ViewDidAppear() 方法中,加入滑动手势。
     
    let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("edgePanGesture:"))
        edgePan.edges = UIRectEdge.Left
        self.view.addGestureRecognizer(edgePan)
     
    •  在手势监听方法中,创建 UIPercentDrivenInteractiveTransition 属性,并实现手势百分比更新。
     
    func 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属性。
     
    func 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协议。
    •  
    •  实现该协议的两个基本方法:
     
    //指定转场动画持续的时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval      
    //转场动画的具体内容       
    func animateTransition(transitionContext: UIViewControllerContextTransitioning)
     
     以上两个步骤和 Push & Pop 的自定义一样,接下来就是不同的。
     
    •  如果使用 Modal 方式从一个 VC 到另一个 VC,那么需要第一个 VC 遵循 UIViewControllerTransitioningDelegate 协议,并实现以下两个协议方法:
    
    //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 动画的百分比。

    //百分比Push
    func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
         return self.percentDrivenTransition
    }
    //百分比Pop
    func 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() 方法裁剪去多余的部分。
    • 分别给两个控制器添加两个按钮,第一个按钮拖线到第二个控制器,第二个控制器绑定一个方法用来dismiss。