转场动画-Swift

效果图

以上是一个关于CollectionViewCell点击展开为一个二级页面的转场动画,支持手势过渡及完成度展现。
主要参考Kitten-Yang的文章做的效果。

UIViewControllerAnimatedTransitioning

官方开发文档
简单来说,这是一个协议。通过创建遵守该协议的对象,可以创建一个动画制作者对象,从而高度定制ViewController的转场动画。不过这个转场必须是不能互动的,如果需要创建支持互动的动画,则必须将你的动画制作者对象与另一个能够控制动画的对象关联起来。

互动支持

为了让转场动画对手势等有互动支持,需要与另一个遵守UIViewControllerInteractiveTransitioning协议的对象进行关联。
一般来说,我们不需要自己去专门写一个类来遵守这个*** UIViewControllerInteractiveTransitioning协议,系统中有一个类名为UIPercentDrivenInteractiveTransition***已经帮我们写好了。

UIPercentDrivenInteractiveTransition

该类基于UIViewControllerInteractiveTransitioning协议创建,为我们提供了三个主要方法:

- updateInteractiveTransition:
- cancelInteractiveTransition
- finishInteractiveTransition

第一个方法可以根据我们传入的progress参数来调整动画的完成度,后两个方法就顾名思义了,一个取消互动动画,一个结束互动动画。

动画思路

基本的类都介绍完了,接下来谈一下动画的思路。思路是最重要的一部分。
从效果图可以看到,从第一个ViewController(以下称FirstViewController)推到第二个ViewController(以下称SecondViewController)的过程中,Cell中的图片变换到了第二个ViewController中图片的位置。其次是一些界面上透明度的变化。
可以总结一句就是说
Cell.imageView.frame -> SecondViewController.imageView.frame
FirstViewController.view.alpha = 0 SecondViewController.alpha = 1
的一个过程。
动画执行的关键就是我们缺少一个容器去处理这样视图位置及透明度的变化。

好在func animateTransition(_ transitionContext: UIViewControllerContextTransitioning)中的transitionContext中有一个ContainView可以在我们进行转场的时候做容器使用。

截取了一部分代码:

 
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! DetailViewController
        let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController
        let containView = transitionContext.containerView()

按上述可以拿到容器View及转场中的两个视图控制器。剩下要做的就是在ContainView中进行Frame等关键属性的变化。
但是需要注意的一点是,我们怎么把Cell中的ImageView提出来然后移到下一个ViewController中?
这时就需要动画中的一点障眼法,我们不需要移动Cell中的ImageView,移动会造成很多不必要的麻烦(还得移回去),但是我们可以给他做一个截图,通过移动截图来营造移动了Cell的ImageView的假象。

下面是截图及初始化的主要部分代码,思路参考注释。


        //获取当前点击的Cell
        let indexPath = fromViewController.collectionView.indexPathsForSelectedItems()![0]
        let cell = fromViewController.collectionView.cellForItemAtIndexPath(indexPath) as! CustomCollectionViewCell
        //制作截图
        let snapShotView = cell.imageView .snapshotViewAfterScreenUpdates(false)
        
        //注意添加的先后顺序,否则会被遮挡。
        containView?.addSubview((toViewController.view)!)
        containView?.addSubview(snapShotView)
        
        //截图在ContainView中的初始位置调整
        snapShotView.frame = (cell.convertRect(cell.imageView.frame, toView: cell.superview!.superview))
        snapShotView.frame = CGRectMake(snapShotView.frame.origin.x, snapShotView.frame.origin.y + 64, snapShotView.frame.size.width, snapShotView.frame.size.height)

        //对变换前后的原视图进行隐藏
        cell.imageView.hidden = true
        toViewController.detailImageView.hidden = true
        
        //设置第二个控制器位置,透明度
        toViewController.view.frame = transitionContext .finalFrameForViewController(toViewController)
        toViewController.view.alpha = 0

动画的变化思路前面已经提过,下面贴上真正的动画部分代码:

         //动画
        UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: UIViewAnimationOptions.CurveLinear, animations: {
            toViewController.view.alpha = 1
            //假装把Cell的ImageView移动到第二个VC中的ImageView的位置。
            snapShotView.frame = (toViewController.view?.convertRect(toViewController.detailImageView.frame, toView: toViewController.view.superview))!
            
            }) { (success) in
                toViewController.detailImageView.hidden = false;
                cell.imageView.hidden = false;
                //删除截图
                snapShotView.removeFromSuperview()
                //完成动画
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
        }

还有一个必须实现的方法是:

func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval

用来决定动画的执行时间

动画的使用

转场代码都可以保持不变,该Push地方Push,该Pop的地方Pop
在FirstViewController中执行

self.navigationController?.delegate = self

当然FirstViewController需要遵守UINavigationControllerDelegate协议。
然后实现

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

具体如下:

   //MARK: - Translation
    func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        if toVC.isKindOfClass(DetailViewController)
            //建议对第二个ViewController进行判断,否则pop回来动画混乱,如果有必要还可以对operation进行判断(push or pop)
        {
            //创建一个你刚写的类的对象即可。
            let transition = MoveAnimation()
            return transition
        }
        else{
            return nil
        }
}

以上就是Push部分动画,Pop回来的时候原理是一样的,只是ImageView的Frame变化反过来,alpha的变化也要反过来,所以可以另写一个Pop的动画类。
贴一个完成的与上对应的Pop动画部分:

import UIKit

class MoveInverseTransition: NSObject,UIViewControllerAnimatedTransitioning {

    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.6
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! DetailViewController
        let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ViewController
        let containView = transitionContext.containerView()
        
        //获取当前点击的Cell
        let indexPath = toViewController.collectionView.indexPathsForSelectedItems()![0]
        let cell = toViewController.collectionView.cellForItemAtIndexPath(indexPath) as! CustomCollectionViewCell
        let snapShotView = fromViewController.detailImageView .snapshotViewAfterScreenUpdates(false)
        containView?.addSubview((toViewController.view)!)
        containView?.addSubview(snapShotView)
        
        snapShotView.frame = (fromViewController.view.convertRect(fromViewController.detailImageView.frame, toView:fromViewController.view.superview))
        cell.imageView.hidden = true
        
        //设置第二个控制器位置,透明度
        toViewController.view.frame = transitionContext .finalFrameForViewController(toViewController)
        toViewController.view.alpha = 0
        
        
        //动画
        UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: UIViewAnimationOptions.CurveLinear, animations: {
            toViewController.view.alpha = 1
            snapShotView.frame = (cell.convertRect(cell.imageView.frame, toView:cell.superview?.superview))
            snapShotView.frame = CGRectMake(snapShotView.frame.origin.x, snapShotView.frame.origin.y + 64, snapShotView.frame.size.width, snapShotView.frame.size.height)

        }){ (success) in
            fromViewController.detailImageView.hidden = false;
            cell.imageView.hidden = false;
            snapShotView.removeFromSuperview()
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
        }
    }

}

动画的使用方式也与上相同。

手势交互

之前介绍过UIPercentDrivenInteractiveTransition,我们的手势交互就是主要建立在它所含的三个方法上。
思路:在动画过渡过程中,通过手势的滑动来计算出一个完成度的Progress(比较常见,比如手势计算缩放比例),执行updateInteractiveTransition:progress 即可完成动画按百分比显示。

手势的设定
    func setupGestureRecognizer() {
        //设置边缘触控手势及其方位
        let edgeGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self,action: #selector(DetailViewController.edgePanGesture(_:)))
        edgeGestureRecognizer.edges = UIRectEdge.Left
        self.view.addGestureRecognizer(edgeGestureRecognizer)
    }
    
    func edgePanGesture(gestureRecognizer:UIScreenEdgePanGestureRecognizer) {
        //计算动画完成度Progress
        var progress = gestureRecognizer.translationInView(self.view).x/self.view.frame.size.width
        progress = min(1.0, max(0.0, progress))
        
        if gestureRecognizer.state == UIGestureRecognizerState.Began{
            //手势开始,执行Pop动作,触发动画
            percentTransition = UIPercentDrivenInteractiveTransition()
            self.navigationController?.popViewControllerAnimated(true)
        }
        else if gestureRecognizer.state == UIGestureRecognizerState.Changed{
            //手势执行过程中,不停通过progress去更新动画状态
            percentTransition?.updateInteractiveTransition(progress)
        }
        else if gestureRecognizer.state == UIGestureRecognizerState.Cancelled || gestureRecognizer.state == UIGestureRecognizerState.Ended {
            //手势取消或者结束,判断是否完成动画或者取消。
            if progress > 0.1
            {
                percentTransition?.finishInteractiveTransition()
            }
            else
            {
                percentTransition?.cancelInteractiveTransition()
            }
        }
        
    }

交互动画的使用(实现两个NavigationController的代理方法):

    func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        if toVC.isKindOfClass(ViewController)
        {
            return MoveInverseTransition()
        }
        else{
            return nil
        }
    }
    
    func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        if animationController.isKindOfClass(MoveInverseTransition)
        {
            return percentTransition
        }
        else
        {
            return nil
        }
    }

完整Demo

以上内容都是在Kitten-Yang的文章基础上作了一些自己的理解,这是一篇学习笔记。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,616评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,020评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,078评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,040评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,154评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,265评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,298评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,072评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,491评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,795评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,970评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,654评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,272评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,985评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,223评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,815评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,852评论 2 351

推荐阅读更多精彩内容