Swift 项目总结 04 - 自定义控制器转场

自定义控制器转场

自定义控制器转场包括 Push 转场、Tabs 切换转场和 Modal 转场,在日常的项目开发中都十分常用,而这些转场动画通常是具有通用性的,所以我在项目开发中采用创建转场代理类来实现。

下面以 Push 为例说明,其他转场类型同理:

1. 创建转场代理类 CustomTransitionDelegate,继承 NSObject
2. 继承 UINavigationControllerDelegate 协议并实现下面的协议方法
// 返回处理 push/pop 转场动画对象,就是对应上面那个表格的代理方法
func navigationController(
    _ navigationController: UINavigationController,
    animationControllerFor operation: UINavigationControllerOperation,
    from fromVC: UIViewController,
    to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
3. 继承 UIViewControllerAnimatedTransitioning 协议并实现下面的协议方法
// 返回转场动画时间
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval
// 执行动画调用
func animateTransition(using transitionContext: UIViewControllerContextTransitioning)
4.【重要】必须在你自定义转场动画结束时调用 UIViewControllerContextTransitioning 上下文对象转场完成
transitionContext.completeTransition(true)
5. 控制器属性持有该转场代理类对象
class ViewController: UIViewController {
    // 自定义的转场代理
    fileprivate var customTransitionDelegate = CustomTransitionDelegate()
}
6. 控制器转场时设置该代理对象(不同情况)
// UITabBarController + Tab
self.tabBarController?.delegate = customTransitionDelegate
// UINavigationController + Push
func pushWithCustomTransition() {
    guard let navigationController = self.navigationController else { return }
    let pushVc = PushViewController()
    navigationController.delegate = customTransitionDelegate
    navigationController.pushViewController(pushVc, animated: true)
}
// UIViewController + Modal
func presentWithCustomTransition() {
    let modalController = ModalViewController()
    modalController.transitioningDelegate = customTransitionDelegate
    self.transitioningDelegate = customTransitionDelegate
    self.present(modalController, animated: true, completion: nil)
}

以下是我实现的具体3种自定义控制器转场代理类例子,分别执行3种动画:渐变、卡片弹出、点扩散,其中渐变转场代理类实现了3种类型转场,其他2个只实现了 Modal 类型转场

渐变转场代理类

class AlphaTransitionDelegate: NSObject, UIViewControllerAnimatedTransitioning {

    // 自定义属性,判断是出现还是消失
    fileprivate var isAppear: Bool = true
    
    /// UIViewControllerTransitioningDelegate 代理方法,返回转场动画时间
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        if self.isAppear {
            return 0.45
        } else {
            return 0.40
        }
    }
    
    /// UIViewControllerTransitioningDelegate 代理方法,处理转场执行动画
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if self.isAppear {
            animateTransitionForAppear(using: transitionContext)
        } else {
            animateTransitionForDisappear(using: transitionContext)
        }
    }
    
    /// 自定义方法,处理出现的转场动画
    fileprivate func animateTransitionForAppear(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
        guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
        guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
        
        let duration = self.transitionDuration(using: transitionContext)
        let containerView = transitionContext.containerView
        containerView.addSubview(fromView)
        containerView.addSubview(toView)
        
        // 渐变动画
        toView.alpha = 0
        UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
            toView.alpha = 1.0
        }, completion: { (_) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        })

    }
    
    /// 自定义方法,处理消失的转场动画
    fileprivate func animateTransitionForDisappear(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
        guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
        guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
        
        let duration = self.transitionDuration(using: transitionContext)
        let containerView = transitionContext.containerView
        containerView.insertSubview(toView, at: 0)

        // 渐变动画
        fromView.alpha = 1.0
        UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
            fromView.alpha = 0
        }, completion: { (_) in
            fromView.removeFromSuperview()
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        })
        
    }
}

// MARK: - UITabBarControllerDelegate 分页转场代理
extension AlphaTransitionDelegate: UITabBarControllerDelegate {
    
    /// 返回处理 tabs 转场动画的对象
    func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isAppear = true
        return self
    }
}

// MARK: - UINavigationControllerDelegate 导航转场代理
extension AlphaTransitionDelegate: UINavigationControllerDelegate {
    
    /// 返回处理 push/pop 转场动画的对象
    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        switch operation {
        case .push:
            isAppear = true
        case .pop:
            isAppear = false
        default:
            return nil
        }
        return self
    }
}

// MARK: - UIViewControllerTransitioningDelegate 弹出转场代理
extension AlphaTransitionDelegate: UIViewControllerTransitioningDelegate {
    
    /// 返回处理 present 转场动画的对象
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // presented 被弹出的控制器,presenting 根控制器,source 源控制器
        self.isAppear = true
        return self
    }
    
    /// 返回处理 dismiss 转场动画的对象
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isAppear = false
        return self
    }
}

卡片转场代理类

class CardTransitionDelegate: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    
    // 自定义属性,判断是 present 还是 dismiss
    fileprivate var isPresent: Bool = true
    fileprivate weak var maskBackgroundView: UIView?
    fileprivate weak var source: UIViewController?
    fileprivate weak var presented: UIViewController?
    // 动画卡片距离顶部的距离
    fileprivate var topForShow: CGFloat = 40

    init(topForShow: CGFloat) {
        super.init()
        self.topForShow = topForShow
    }
    
    /// 代理方法,返回处理 present 转场动画的对象
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // presented - 被弹出控制器,presenting - 根控制器(Navigation/Tab/View),source - 源控制器
        // 因为使用了 overFullScreen,source 不会调用 viewWillDisappear 和 viewDidDisappear,这里手动触发
        source.viewWillDisappear(false)
        source.viewDidDisappear(false)
        self.source = source
        self.presented = presented
        self.isPresent = true
        return self
    }
    
    /// 代理方法,返回处理 dismiss 转场动画的对象
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isPresent = false
        return self
    }
    
    /// 代理方法,返回 present 或者 dismiss 的转场时间
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        if self.isPresent { // present
            return 0.45
        } else { // dismiss
            return 0.45
        }
    }
    
    /// 代理方法,处理 present 或者 dismiss 的转场,这里分离出 2 个子方法分别处理 present 和 dismiss
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if self.isPresent { // present
            animateTransitionForPresent(using: transitionContext)
        } else { // dismiss
            animateTransitionForDismiss(using: transitionContext)
        }
    }
    
    /// 自定义方法,处理 present 转场
    fileprivate func animateTransitionForPresent(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
        guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
        guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
        
        let duration = self.transitionDuration(using: transitionContext)
        let containerView = transitionContext.containerView
        containerView.addSubview(fromView)
        
        // 灰色背景控件
        let maskBackgroundView = UIView(frame: containerView.bounds)
        maskBackgroundView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
        maskBackgroundView.alpha = 0.0
        maskBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CardTransitionDelegate.clickMaskViewAction(_:))))
        self.maskBackgroundView = maskBackgroundView
        fromView.addSubview(maskBackgroundView)
        containerView.addSubview(toView)
        
        // 动画开始,底层控制器往后缩小,灰色背景渐变出现,顶层控制器从下往上出现
        let tranformScale = (UIScreen.main.bounds.height - self.topForShow) / UIScreen.main.bounds.height
        let tranform = CGAffineTransform(scaleX: tranformScale, y: tranformScale)
        toView.frame.origin.y = UIScreen.main.bounds.height
        UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
            toView.frame.origin.y = self.topForShow
            maskBackgroundView.alpha = 1.0
            fromView.transform = tranform
        }, completion: { (_) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        })
        
    }
    
    /// 自定义方法,处理 dismiss 转场
    fileprivate func animateTransitionForDismiss(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
        guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
        guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
        
        let duration = self.transitionDuration(using: transitionContext)

        // 动画还原
        UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
            fromView.frame.origin.y = UIScreen.main.bounds.height
            self.maskBackgroundView?.alpha = 0.0
            toView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
        }, completion: { (_) in
            self.maskBackgroundView?.removeFromSuperview()
            // 注意!:因为外面使用了 overFullScreen ,dismiss 会丢失视图,需要自己手动加上
            UIApplication.shared.keyWindow?.insertSubview(toView, at: 0)
            // 因为使用了 overFullScreen,导致 source 没法正常调用 viewWillAppear 和 viewDidAppear,这里手动触发
            if let source = self.source {
                source.viewWillAppear(false)
                source.viewDidAppear(false)
            }
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        })
    }
    
    /// 点击灰色背景事件处理
    func clickMaskViewAction(_ gestureRecognizer: UITapGestureRecognizer) {
        self.presented?.dismiss(animated: true, completion: nil)
    }
}

点扩散转场代理类

class RippleTransitionDelegate: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    
    // 自定义属性,判断是 present 还是 dismiss
    fileprivate var isPresent: Bool = true
    fileprivate weak var transitionContext: UIViewControllerContextTransitioning?
    // 起始点坐标
    var startOrigin: CGPoint = CGPoint.zero
    // 扩散半径
    fileprivate var radius: CGFloat = 0
    
    init(startOrigin: CGPoint = .zero) {
        super.init()
        self.startOrigin = startOrigin
        
        // 这里取扩散最大半径,即屏幕的对角线长
        let screenWidth = ceil(UIScreen.main.bounds.size.width)
        let screenHeight = ceil(UIScreen.main.bounds.size.height)
        self.radius = sqrt((screenWidth * screenWidth) + (screenHeight * screenHeight))
    }
    
    /// 代理方法,返回处理 present 转场动画的对象
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isPresent = true
        return self
    }
    
    /// 代理方法,返回处理 dismiss 转场动画的对象
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isPresent = false
        return self
    }
    
    /// 代理方法,返回 present 或者 dismiss 的转场时间
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        if self.isPresent { // present
            return 0.45
        } else { // dismiss
            return 0.40
        }
    }
    
    /// 代理方法,处理 present 或者 dismiss 的转场,这里分离出 2 个子方法分别处理 present 和 dismiss
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        self.transitionContext = transitionContext
        if self.isPresent { // present
            animateTransitionForPresent(using: transitionContext)
        } else { // dismiss
            animateTransitionForDismiss(using: transitionContext)
        }
    }
    
    /// 自定义方法,处理 present 转场
    fileprivate func animateTransitionForPresent(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
        guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
        guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
        
        let duration = self.transitionDuration(using: transitionContext)
        let containerView = transitionContext.containerView
        containerView.addSubview(fromView)
        containerView.addSubview(toView)
        
        // 计算动画图层开始和结束路径
        let startFrame = CGRect(origin: self.startOrigin, size: .zero)
        let maskStartPath = UIBezierPath(ovalIn: startFrame)
        let maskEndPath = UIBezierPath(ovalIn: startFrame.insetBy(dx: -self.radius, dy: -self.radius))
        
        // 创建动画图层, layer.mask 属性是表示显示的范围
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskEndPath.cgPath
        toView.layer.mask = maskLayer
        
        // 为动画图层添加路径,从一个点开始扩散到整屏
        let maskLayerAnimation = CABasicAnimation(keyPath: "path")
        maskLayerAnimation.fromValue = maskStartPath.cgPath
        maskLayerAnimation.toValue = maskEndPath.cgPath
        maskLayerAnimation.duration = duration
        maskLayerAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        maskLayerAnimation.delegate = self
        maskLayer.add(maskLayerAnimation, forKey: "ripple_push_animation")
        
    }
    
    /// 自定义方法,处理 dismiss 转场
    fileprivate func animateTransitionForDismiss(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
        guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
        guard let fromView = fromViewController.view, let toView = toViewController.view else { return }
        
        let duration = self.transitionDuration(using: transitionContext)
        let containerView = transitionContext.containerView
        containerView.insertSubview(toView, at: 0)
        
        // 计算动画图层开始和结束路径
        let startFrame = CGRect(origin: self.startOrigin, size: .zero)
        let maskStartPath = UIBezierPath(ovalIn: startFrame.insetBy(dx: -self.radius, dy: -self.radius))
        let maskEndPath = UIBezierPath(ovalIn: startFrame)
        
        // 创建动画图层,layer.mask 属性是表示显示的范围
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskEndPath.cgPath
        fromView.layer.mask = maskLayer
        
        // 为动画图层添加路径,从整屏收缩到一个点
        let maskLayerAnimation = CABasicAnimation(keyPath: "path")
        maskLayerAnimation.fromValue = maskStartPath.cgPath
        maskLayerAnimation.toValue = maskEndPath.cgPath
        maskLayerAnimation.duration = duration
        maskLayerAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        maskLayerAnimation.delegate = self
        maskLayer.add(maskLayerAnimation, forKey: "ripple_dimiss_animation")
    }
}

// MARK: - CAAnimationDelegate
extension RippleTransitionDelegate: CAAnimationDelegate {
    /// 动画结束后调用
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        // 把 layer.mask 赋值为 nil,是为了释放动画图层
        if let transitionContext = self.transitionContext {
            if let toViewController = transitionContext.viewController(forKey: .to) {
                toViewController.view.layer.mask = nil
            }
            if let fromViewController = transitionContext.viewController(forKey: .from) {
                fromViewController.view.layer.mask = nil
            }
            transitionContext.completeTransition(true)
        }
    }
}

这三个转场代理类的 Demo 代码在这:CustomTransitionDemo

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

推荐阅读更多精彩内容