swift 深入解析push 和 present自定义转场动画

学习一下push和present的自定义转场动画。
demo地址:https://github.com/weiman152/TransitionDemo
从iOS7开始,苹果更新了自定义ViewController转场的API。

几个protocol:
讲自定义转场就离不开这几个protocol:

UIViewControllerContextTransitioning
UIViewControllerAnimatedTransitioning
UIViewControllerInteractiveTransitioning
UIViewControllerTransitioningDelegate
UINavigationControllerDelegate
UITabBarControllerDelegate

我们这个demo中就使用了
UIViewControllerContextTransitioning,
UIViewControllerAnimatedTransitioning,
UIViewControllerTransitioningDelegate,
UINavigationControllerDelegate。

实现效果:
push:


QQ20181026-211948.gif

present:

QQ20181027-183358.gif
3333.gif

源码:

PushTransition

//
//  PushTransition.swift
//  TransitionDemo
//
//  Created by iOS on 2018/10/26.
//  Copyright © 2018年 weiman. All rights reserved.
//

import UIKit

class PushTransition: NSObject {
    
    enum `Type` {
        case scale
        case formTop
        case fromBottom
    }
    
    private let ScreenWidth = UIScreen.main.bounds.size.width
    private let ScreenHeight = UIScreen.main.bounds.size.height
    
    static private var duration = 0.5
    static private var type: Type = .scale
    // 设置转场代理
    static var transition = PushTransition()
    
    /// 带动画的push
    ///
    /// - Parameters:
    ///   - fromVC: 发起push操作的VC
    ///   - toVC: 即将被push出来的VC
    ///   - type: 需要哪种动画
    ///   - duration: 动画执行的时间
    static func pushWithTransition(fromVC: UIViewController,
                                   toVC: UIViewController,
                                   type: Type = .scale,
                                   duration: Double = 0.5) {
        self.type = type
        self.duration = duration
        fromVC.navigationController?.delegate = PushTransition.transition
        fromVC.navigationController?.pushViewController(toVC, animated: true)
        fromVC.navigationController?.delegate = nil
    }

}

extension PushTransition: UIViewControllerAnimatedTransitioning {
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        
        return PushTransition.duration
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        let toVC = transitionContext.viewController(forKey: .to)
        let fromVC = transitionContext.viewController(forKey: .from)
        
        guard let fromView = fromVC?.view,
            let toView = toVC?.view else {
                return
        }
        
        switch PushTransition.type {
        case .scale:
            scale(fromView: fromView,
                  toView: toView,
                  transitionContext: transitionContext)
        case .formTop:
            fromTop(fromView: fromView,
                    toView: toView,
                    transitionContext: transitionContext)
        case .fromBottom:
            fromBottom(fromView: fromView,
                       toView: toView,
                       transitionContext: transitionContext)
        }
    }
}

extension PushTransition: UINavigationControllerDelegate {
    
    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        return PushTransition()
    }
}

extension PushTransition {

    /// 缩放的push
    ///
    /// - Parameters:
    ///   - fromView: 发起push操作的VC的View
    ///   - toView: 即将被push出来的VC的view
    ///   - transitionContext: 上下文
    private func scale(fromView: UIView,
                       toView: UIView,
                       transitionContext: UIViewControllerContextTransitioning)
    {
        transitionContext.containerView.addSubview(toView)
        transitionContext.containerView.bringSubviewToFront(fromView)
        
        UIView.animate(withDuration: PushTransition.duration, animations: {
            
            fromView.alpha = 0
            fromView.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
            toView.alpha = 1.0
            
        }) { (_) in
            
            fromView.transform = CGAffineTransform(scaleX: 1, y: 1)
            transitionContext.completeTransition(true)
            fromView.alpha = 1.0
        }
    }
    
    /// 从上到下的push
    ///
    /// - Parameters:
    ///   - fromView: 发起push操作的VC的View
    ///   - toView: 即将被push出来的VC的view
    ///   - transitionContext: 上下文
    private func fromTop(fromView: UIView,
                         toView: UIView,
                         transitionContext: UIViewControllerContextTransitioning)
    {
        transitionContext.containerView.addSubview(toView)
        
        toView.transform = CGAffineTransform(translationX: 0,
                                             y: -self.ScreenHeight)
        UIView.animate(withDuration: PushTransition.duration, animations: {
            toView.transform = CGAffineTransform(translationX: 0, y: 0)
            toView.alpha = 1.0
            
        }) { (_) in
            transitionContext.completeTransition(true)
        }
    }
    
    /// 从下往上的push
    ///
    /// - Parameters:
    ///   - fromView: 发起push操作的VC的View
    ///   - toView: 即将被push出来的VC的view
    ///   - transitionContext: 上下文
    private func fromBottom(fromView: UIView,
                            toView: UIView,
                            transitionContext:  UIViewControllerContextTransitioning)
    {
        transitionContext.containerView.addSubview(toView)
        
        toView.transform = CGAffineTransform(translationX: 0,
                                             y: self.ScreenHeight)
        UIView.animate(withDuration: PushTransition.duration, animations: {
            toView.transform = CGAffineTransform(translationX: 0, y: 0)
            toView.alpha = 1.0
            
        }) { (_) in
            transitionContext.completeTransition(true)
        }
        
    }
}

PresentTransition:

//
//  PresentTransition.swift
//  TransitionDemo
//
//  Created by iOS on 2018/10/26.
//  Copyright © 2018年 weiman. All rights reserved.
//

import UIKit

class PresentTransition: NSObject {
    
    enum Animate {
        case scale
        case fromLeft
        case fromRight
    }
    
    enum Transition {
        case present
        case dismiss
    }
    
    private let ScreenWidth = UIScreen.main.bounds.size.width
    private let ScreenHeight = UIScreen.main.bounds.size.height
    // 设置转场代理
    static private let transition = PresentTransition()
    
    static private var duration = 1.0
    static private var type: Animate = .scale
    static private var tran: Transition = .present
    
    static func presentWithAnimate(fromVC: UIViewController,
                            toVC: UIViewController,
                            duration: Double = 1.0,
                            animate: Animate = .scale) {
        PresentTransition.duration = duration
        PresentTransition.type = animate
        
        toVC.transitioningDelegate = PresentTransition.transition
        fromVC.present(toVC, animated: true) { }
    }

}

extension PresentTransition: UIViewControllerAnimatedTransitioning {
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return PresentTransition.duration
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        switch PresentTransition.tran {
        case .present:
            presentTransition(transitionContext: transitionContext)
        case .dismiss:
            dismissTransition(transitionContext: transitionContext)
        }
    }
}

extension PresentTransition: UIViewControllerTransitioningDelegate {
    
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        PresentTransition.tran = .present
        return PresentTransition()
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        PresentTransition.tran = .dismiss
        return PresentTransition()
    }
}

extension PresentTransition {
    
    private func presentTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let toVC = transitionContext.viewController(forKey: .to)
        let fromVC = transitionContext.viewController(forKey: .from)
        
        guard let fromView = fromVC?.view,
            let toView = toVC?.view else {
                return
        }
        
        transitionContext.containerView.addSubview(toView)
        
        switch PresentTransition.type {
        case .scale:
            scalePresent(fromView: fromView,
                         toView: toView,
                         transitionContext: transitionContext)
        case .fromLeft:
            fromLeftPresent(fromView: fromView,
                            toView: toView,
                            transitionContext: transitionContext)
        case .fromRight:
            fromRightPresent(fromView: fromView,
                             toView: toView,
                             transitionContext: transitionContext)
        }
        
    }
    
    private func dismissTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let toVC = transitionContext.viewController(forKey: .to)
        let fromVC = transitionContext.viewController(forKey: .from)
        
        guard let fromView = fromVC?.view,
            let toView = toVC?.view else {
                return
        }
        
        switch PresentTransition.type {
        case .scale:
            scaleDismiss(fromView: fromView,
                         toView: toView,
                         transitionContext: transitionContext)
        case .fromLeft:
            fromLeftDismiss(fromView: fromView,
                            toView: toView,
                            transitionContext: transitionContext)
        case .fromRight:
            fromRightDismiss(fromView: fromView,
                             toView: toView,
                             transitionContext: transitionContext)
        }
    }
    
    private func scalePresent(fromView: UIView,
                              toView: UIView,
                              transitionContext: UIViewControllerContextTransitioning)
    {
        toView.alpha = 0.0
        toView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
        UIView.animate(withDuration: PresentTransition.duration, animations: {
            toView.alpha = 1.0
            toView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
        }) { (_) in
            toView.alpha = 1.0
            toView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
            transitionContext.completeTransition(true)
        }
    }
    
    private func scaleDismiss(fromView: UIView,
                              toView: UIView,
                              transitionContext: UIViewControllerContextTransitioning)
    {
        transitionContext.containerView.insertSubview(toView, belowSubview: fromView)
        UIView.animate(withDuration: PresentTransition.duration, animations: {
            fromView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
        }) { (_) in
            transitionContext.completeTransition(true)
        }
    }
    
    private func fromLeftPresent(fromView: UIView,
                                 toView: UIView,
                                 transitionContext: UIViewControllerContextTransitioning)
    {
        toView.frame = CGRect(x: -ScreenWidth, y: 0, width: ScreenWidth, height: ScreenHeight)
        UIView.animate(withDuration: PresentTransition.duration, animations: {
            toView.frame = CGRect(x: 0, y: 0, width: self.ScreenWidth, height: self.ScreenHeight)
            toView.layoutSubviews()
        }) { (_) in
            transitionContext.completeTransition(true)
        }
        
    }
    
    private func fromLeftDismiss(fromView: UIView,
                                 toView: UIView,
                                 transitionContext: UIViewControllerContextTransitioning)
    {
        transitionContext.containerView.insertSubview(toView, belowSubview: fromView)
        UIView.animate(withDuration: PresentTransition.duration, animations: {
            fromView.transform = CGAffineTransform(translationX: 0, y: self.ScreenHeight)
            fromView.alpha = 0
        }) { (_) in
            transitionContext.completeTransition(true)
        }
    }
    
    private func fromRightPresent(fromView: UIView,
                                  toView: UIView,
                                  transitionContext: UIViewControllerContextTransitioning)
    {
        toView.frame = CGRect(x: ScreenWidth, y: 0, width: ScreenWidth, height: ScreenHeight)
        UIView.animate(withDuration: PresentTransition.duration, animations: {
            toView.frame = CGRect(x: 0, y: 0, width: self.ScreenWidth, height: self.ScreenHeight)
            toView.layoutSubviews()
        }) { (_) in
            transitionContext.completeTransition(true)
        }
    }
    
    private func fromRightDismiss(fromView: UIView,
                                  toView: UIView,
                                  transitionContext: UIViewControllerContextTransitioning)
    {
        transitionContext.containerView.insertSubview(toView, belowSubview: fromView)
        UIView.animate(withDuration: PresentTransition.duration, animations: {
            fromView.transform = CGAffineTransform(translationX: 0, y: self.ScreenHeight)
            fromView.alpha = 0
        }) { (_) in
            transitionContext.completeTransition(true)
        }
    }
}

参考文章:
https://www.jianshu.com/p/e7155f938e59

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

推荐阅读更多精彩内容

  • 2018年9月24日 星期一 农历八月十五,中秋节。 中秋月。 但愿人长久,千里共婵娟。 阴晴圆缺都休说,且喜人...
    涓滴汇海阅读 174评论 0 5
  • 刚刚升级了简书。 感觉这个最新版本太好了,以后可能都舍不得升级了! 好久没升级,跨过好几个版本,今天提示升级,升级...
    方知甬阅读 217评论 0 0