SideNavigation——今晚不加班😂

前言

在 Android app 中,侧边栏的应用是非常普遍的,从 Google 的官方 UI 设计指南中可以看出这种设计对 UI || UED 的引导,不仅如此,Google 自家的应用也对侧边栏进行了广泛的实践,inbox gmail 就是其中之一。因此,你也可能遇到有一天你的 UI || UED 跑过来对你说我们 iOS 也支持一下 “侧边栏” 导航吧。如果你有这个需求又恰好看到这篇文章,那么恭喜你,本来可能需要加班的你可以解放了。

image.png

正文

如上图,像这样的效果实现方式很多,我们项目中原来就有实现过,既然实现过,那么为什么还要去实现一遍呢?这就要从我苦逼的 iPad 适配之旅开始讲了,我们的项目是一个 OC + Swift + RN + H5 的一个混合项目,适配起来那个酸爽别提了,侧边是由 OC 写的老旧代码,在 iPad 的横竖屏适配上特别糟糕😰,于是我决定用 Swift 封装一个 SideNavigation 的轮子。为了满足需求这个轮子应该具备以下特点:

  1. 横竖屏适配,满足 iPad 适配需求
  2. 支持 Swift && OC 满足混编需求
  3. 用户可以通过向右或者向左滑动呼出侧边栏
  4. 用户还可以通过拖拽关闭侧边栏
接口要简单

把复杂留给自己,简单留给他人,好的接口大底应该如此。如:

public convenience init(_ viewController: UIViewController, left: UIViewController) 
public convenience init(_ viewController: UIViewController, right: UIViewController)

由上可知,我们只需要通过初始化一个 SideMenuManager 就能实现你想要的侧边抽屉效果,实在是太方便了😂。

实现

(1) 实现 UIViewControllerTransitioningDelegate
   我们可以通过 UIViewControllerTransitioningDelegate 来实现转场动画:

    public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        let presentationController = PresentationController(presentedViewController: presented, presenting: presenting)
        presentationController.delegate = self
        presentationController.direction = direction
        self.dismissInteractor = PercentDrivenInteractiveTransition(self.presentController, with: presentationController.dimmingView, present: nil, direction: self.direction)
        return presentationController
    }

    public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animator = AnimatedTransitioning()
        animator.direction = direction
        animator.transitionType = .dismiss
        return animator
    }

    public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animator = AnimatedTransitioning()
        animator.direction = direction
        animator.transitionType = .present
        return animator
    }

    public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        return self.dismissInteractor.isInteractiveTransition ? self.dismissInteractor : nil
    }

    public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        return self.presentInteractor.isInteractiveTransition ? self.presentInteractor : nil
    }

通过使用 SideNavigation 我们可以知道,我们的侧边效果是通过转场来实现的,要达到侧边栏的效果,我们可以自定义转场动画,👆代码中的代理就是转场协议的实现,包括对 non-interactive 和 interactive 动画进行自定义实现。

(2)自定义 UIPresentationController
   在 public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? 函数中我们需要返回一个指定的 UIPresentationController, 当然,我们这里需要对我们的 UIPresentationController 适当的做一些改造来满足我们的需求:

   // MARK: - Initializers
    override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
        super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
    }

    override var frameOfPresentedViewInContainerView: CGRect {
        var frame: CGRect = super.frameOfPresentedViewInContainerView
        switch direction {
        case .right:
            frame.origin.x = frame.size.width / 3
        default:
            break
        }
        frame.size = size(forChildContentContainer: presentedViewController, withParentContainerSize: containerView!.bounds.size)
        return frame
    }

    override func containerViewWillLayoutSubviews() {
        presentedView?.frame = frameOfPresentedViewInContainerView
    }

    override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize {
        return CGSize(width: parentSize.width*(2.0/3.0), height: parentSize.height)
    }

    override func presentationTransitionWillBegin() {
        containerView?.insertSubview(dimmingView, at: 0)
        NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[dimmingView]|", options: [], metrics: nil, views: ["dimmingView": dimmingView]))
        NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[dimmingView]|", options: [], metrics: nil, views: ["dimmingView": dimmingView]))
        guard let coordinator = presentedViewController.transitionCoordinator else {
            dimmingView.alpha = 1.0
            return
        }

        coordinator.animate(alongsideTransition: { _ in
            self.dimmingView.alpha = 1.0
        })
    }

    override func dismissalTransitionWillBegin() {
        guard let coordinator = presentedViewController.transitionCoordinator else {
            dimmingView.alpha = 0.0
            return
        }

        coordinator.animate(alongsideTransition: { _ in
            self.dimmingView.alpha = 0.0
        })
    }

    lazy var dimmingView: UIView = {
        let dimming = UIView()
        dimming.translatesAutoresizingMaskIntoConstraints = false
        dimming.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
        dimming.alpha = 0.0
        let recognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
        dimming.addGestureRecognizer(recognizer)
        return dimming
    }()

    @objc dynamic func handleTap(recognizer: UITapGestureRecognizer) {
        presentingViewController.dismiss(animated: true)
    }

在自定义的 UIPresentationController 的过程中,我们对 presentedViewframe 进行简单的更改,已达到我们的期望。从效果图中我们也看到,我们还需要一个 dimmingView 来实现半透明效果,这里我们还未它添加了一个手势以便于 dismiss 抽屉。

(3)实现 UIViewControllerAnimatedTransitioning

public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? 需要返回一个 UIViewControllerAnimatedTransitioning 这里我们来初略的看一下:

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return kAnimationDuration
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let from = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
        let to = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
        switch transitionType {
        case .present:
            animatePresenting(in: transitionContext, to: to!, from: from!)
        case .dismiss:
            animateDismissing(in: transitionContext, to: to!, from: from!)
        }
    }

    func animatePresenting(in transitionContext: UIViewControllerContextTransitioning, to: UIViewController, from: UIViewController) {
        var fromRect = transitionContext.initialFrame(for: from)
        var toRect = fromRect
        switch direction {
        case .left:
            toRect.origin.x = -toRect.width / 3 * 2 // for the edge panGesture
            if #available(iOS 11, *) {
                // it's maybe a bug of iOS 11, it should be checked some time
                fromRect = CGRect(x: fromRect.minX - (toRect.width / 3)/2, y: fromRect.minY, width: fromRect.width, height: fromRect.height)
            }
        case .right:
            toRect.origin.x = toRect.width / 3 * 2
            if #available(iOS 11, *) {
                // it's maybe a bug of iOS 11, it should be checked some time
                fromRect = CGRect(x: fromRect.minX + (toRect.width / 3)/2, y: fromRect.minY, width: fromRect.width, height: fromRect.height)
            }
        }
        to.view.frame = toRect
        transitionContext.containerView.addSubview(to.view)
        UIView.animate(withDuration: kAnimationDuration, animations: {
            to.view.frame = fromRect
        }) { (_) in
            if transitionContext.transitionWasCancelled {
                transitionContext.completeTransition(false)
            } else {
                transitionContext.completeTransition(true)
            }
        }
    }

    func animateDismissing(in transitionContext: UIViewControllerContextTransitioning, to: UIViewController, from: UIViewController) {
        var fromRect = transitionContext.initialFrame(for: from)
        switch direction {
        case .left:
            fromRect.origin.x = -fromRect.width
        case .right:
            fromRect.origin.x = fromRect.width
        }
        UIView.animate(withDuration: kAnimationDuration, animations: {
            from.view.frame = fromRect
        }) { (_) in
            if transitionContext.transitionWasCancelled {
                transitionContext.completeTransition(false)
            } else {
                transitionContext.completeTransition(true)
            }
        }
    }

animatePresenting 以及 animateDismissing 我们可以清晰的看到,这里就是对转场这个过程的 startend 过程的位置状态做一个约束,然后在辅以简单的动画。

(4)UIPercentDrivenInteractiveTransition 的继承
   还记得我们在第一步实现的 func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? && func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? 这两个函数吗?我们的用户交互效果就是通过这两个函数来实现的,在这里我们对 UIPercentDrivenInteractiveTransition 进行自定义:

    convenience init(_ viewController: UIViewController, with view: UIView?, present: UIViewController?, direction: Direction? = .left) {
        self.init()
        self.viewController = viewController
        self.direction = direction ?? .left
        self.presentViewController = present
        if self.presentViewController != nil {
            switch self.direction {
            case .left:
                let edgePanGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(onPan(sender:)))
                edgePanGesture.edges = .left
                edgePanGesture.delegate = self
                self.viewController.view.addGestureRecognizer(edgePanGesture)
            case .right:
                let edgePanGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(onPan(sender:)))
                edgePanGesture.edges = .right
                edgePanGesture.delegate = self
                self.viewController.view.addGestureRecognizer(edgePanGesture)
                break
            }
        } else {
            let panGesture = UIPanGestureRecognizer(target: self, action: #selector(onPan(sender:)))
            view?.addGestureRecognizer(panGesture)
            let dismissPanGesture = UIPanGestureRecognizer(target: self, action: #selector(onPan(sender:)))
            self.viewController.view.addGestureRecognizer(dismissPanGesture)
        }
    }

    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {

        /// to avoid the interactivePopGestureRecognizer of UINavigationController
        if let nav = viewController as? UINavigationController {
            return nav.viewControllers.count < 2
        }
        return true
    }

    @objc func onPan(sender: UIPanGestureRecognizer) {
        let  translation = sender.translation(in: sender.view?.superview)
        switch sender.state {
        case .began:
            self.isInteractiveTransition = true
            if self.presentViewController != nil {
                self.viewController.present(self.presentViewController!, animated: true, completion: nil)
            } else {
                self.viewController.dismiss(animated: true, completion: nil)
            }
        case .changed:
            let screenWidth = -UIScreen.main.bounds.size.width
            var dragAmount = self.presentViewController == nil ? screenWidth : -screenWidth
            switch direction {
            case .left:
                dragAmount = self.presentViewController == nil ? screenWidth : -screenWidth
            case .right:
                dragAmount = self.presentViewController != nil ? screenWidth : -screenWidth
            }
            let threshold: CGFloat = 0.20
            var percent = translation.x / dragAmount
            percent = max(percent, 0.0)
            percent = min(percent, 1.0)
            update(percent)
            self.shouldComplete = percent > threshold
        case .cancelled, .ended:
            self.isInteractiveTransition = false
            if self.shouldComplete == false || sender.state == .cancelled {
                cancel()
            } else {
                finish()
            }
        default:
            break
        }
    }

UIPercentDrivenInteractiveTransition 自定义的主要目的是对 转场动效的更新过程进行控制:

    // These methods should be called by the gesture recognizer or some other logic
    // to drive the interaction. This style of interaction controller should only be
    // used with an animator that implements a CA style transition in the animator's
    // animateTransition: method. If this type of interaction controller is
    // specified, the animateTransition: method must ensure to call the
    // UIViewControllerTransitionParameters completeTransition: method. The other
    // interactive methods on UIViewControllerContextTransitioning should NOT be
    // called. If there is an interruptible animator, these methods will either scrub or continue 
    // the transition in the forward or reverse directions.
    open func update(_ percentComplete: CGFloat)

正是如此,我们在 UIPercentDrivenInteractiveTransition 的自定义过程中,通过对 中间视图和侧边视图添加手势来控制转场 update 的进度。
  看看项目中的使用效果:

Simulator Screen Shot - iPhone 8 - 2017-09-22 at 09.45.13.png
Simulator Screen Shot - iPhone X - 2017-09-22 at 10.15.15.png

总结

实现一个简易的侧边抽屉效果还是很简单的,我们通过实现专场协议,自定义转场动画,添加滑动手势,设置转场始末位置状态,就可以轻松搞定侧边栏。

Project

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

推荐阅读更多精彩内容