继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

执着丶执念
关注TA
已关注
手记 18
粉丝 50
获赞 90

自定义控制器转场

自定义控制器转场包括 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

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP