Swift实现一个交互友好&灵活自定义的弹框

前言

在我们平时日常开发中,经常会遇到各种样式的弹框。你是否也经常遇到呢?你是如何实现的?
本文介绍使用UIPresentationController,结合自定义转场动效,实现一个高度自定义的弹框,这也是苹果比较推荐的一种实现方式。

预备知识

开始之前,我们要了解下几个知识点:

  • UIPresentationController
  • UIViewControllerTransitioningDelegate
  • UIViewControllerAnimatedTransitioning

1、UIPresentationController是什么?官方文档中介绍如下:

An object that manages the transition animations and the presentation of view controllers onscreen.

简单来说,它可以管理转场动画和模态出来的窗口控制器。详细信息可以参考:UIPresentationController文档

2、UIViewControllerTransitioningDelegate定义了转场代理方法,可以指定PresentedDismissed动画,以及UIPresentationController

3、UIViewControllerAnimatedTransitioning就是转场动画协议,我们可以遵守该协议,实现转场动画。

实现

1、自定义UIPresentationController,并实现相应方法

struct ZCXPopup {}

extension ZCXPopup {

    class PresentationController: UIPresentationController {

        override func presentationTransitionWillBegin() {
            guard let containerView else { return }
            dimmingView.frame = containerView.bounds
            dimmingView.alpha = 0.0
            containerView.insertSubview(dimmingView, at: 0)

            // 背景蒙层淡入动画
            presentedViewController.transitionCoordinator?.animate { _ in
                self.dimmingView.alpha = 1.0
            }
        }

        override func dismissalTransitionWillBegin() {
            // 背景蒙层淡出动画,以及移除操作
            presentedViewController.transitionCoordinator?.animate(alongsideTransition: { _ in
                self.dimmingView.alpha = 0.0
            }, completion: { _ in
                self.dimmingView.removeFromSuperview()
            })
        }

        override var frameOfPresentedViewInContainerView: CGRect { UIScreen.main.bounds }

        override func containerViewWillLayoutSubviews() {

            guard let containerView else { return }
            dimmingView.frame = containerView.bounds

            guard let presentedView else { return }
            presentedView.frame = frameOfPresentedViewInContainerView
        }

        // MARK: -

        /// 背景蒙层
        private lazy var dimmingView: UIView = {
            let view = UIView()
            view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            return view
        }()
    }
}

代码比较简单,主要的工作就是添加了一个背景蒙层,以及蒙层的动画交互处理,加上子视图尺寸的控制。

注:上面的ZCXPopup结构体没有实际作用,仅仅是为了区分命名空间。

2、UIViewControllerAnimatedTransitioning实现类实现

extension ZCXPopup {

    class TransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {

        private var isOpen: Bool = false

        convenience init(isOpen: Bool = false) {
            self.init()
            self.isOpen = isOpen
        }

        func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
            transitionContext?.isAnimated == true ? 0.5 : 0
        }

        func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

            guard let fromView = transitionContext.viewController(forKey: .from)?.view else { return }
            guard let toView = transitionContext.viewController(forKey: .to)?.view else { return }

            if isOpen {
                transitionContext.containerView.addSubview(toView)
                toView.transform = .init(scaleX: 0.7, y: 0.7)
                toView.alpha = 0
            }

            UIView.animate(
                withDuration: transitionDuration(using: transitionContext),
                delay: 0,
                usingSpringWithDamping: 0.7,
                initialSpringVelocity: 0.7,
                options: []) {
                if self.isOpen {
                    toView.transform = .identity
                    toView.alpha = 1
                } else {
                    fromView.transform = .init(scaleX: 0.7, y: 0.7)
                    fromView.alpha = 0
                }
            } completion: { _ in
                let wasCancelled = transitionContext.transitionWasCancelled
                transitionContext.completeTransition(!wasCancelled)
            }
        }
    }
}

这个实现类的内容也较简单,主要是设置转场动画时长,以及实现转场动画,转场动画分为进场(present)和出场(dismiss)动画。

3、UIViewControllerTransitioningDelegate实现类实现

extension ZCXPopup {

    class TransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {

        func presentationController(
            forPresented presented: UIViewController,
            presenting: UIViewController?,
            source: UIViewController
        ) -> UIPresentationController? {
            PresentationController(presentedViewController: presented, presenting: presenting)
        }

        func animationController(
            forPresented presented: UIViewController,
            presenting: UIViewController,
            source: UIViewController
        ) -> UIViewControllerAnimatedTransitioning? {
            TransitionAnimator(isOpen: true)
        }

        func animationController(
            forDismissed dismissed: UIViewController
        ) -> UIViewControllerAnimatedTransitioning? {
            TransitionAnimator(isOpen: false)
        }
    }
}

在该实现类中,实现代理方法,分别返回自定义的PresentationControllerTransitionAnimator即可。

4、为控制器增加一个扩展,方便使用弹框交互

extension UIViewController {

    /// 转场类型,方便后续扩展
    @objc public enum TransitioningType: Int {
        case none  = 0
        case popup = 1
    }

    /// 设置转场类型
    @objc public var transitioningType: TransitioningType {
        get { getAssociatedObject() as? TransitioningType ?? .none }
        set {
            if newValue == .popup {
                transitioningDelegate = self.popupTransitioningDelegate
                modalPresentationStyle = .custom
            }
            setAssociatedObject(newValue)
        }
    }

    /// transitioningDelegate 实现类,需要被持有
    private var popupTransitioningDelegate: ZCXPopup.TransitioningDelegate {
        lazyVarAssociatedObject { ZCXPopup.TransitioningDelegate() }
    }
}

到这里,一个轻量级的弹窗管理就封装好了。我们就可以给任意一个控制器加上这个交互。

自定义弹框

上面只是封装了弹框的交互,那么我们要怎么实现一个弹框呢?
很简单,具体来说就是,创建一个控制器,将其view设置成透明,然后在其中间加上弹框内容视图contentView。然后,设置控制器的transitioningType = .popup,使用present方式打开即可。

这里大家可能会问,为什么不直接修改控制器的preferredContentSize,而是弄了一个背景透明的全屏控制器。这个问题非常好,欢迎留言讨论。

设置转场类型和打开弹框:

@IBAction func showPopup(_ sender: Any) {
    let sb = UIStoryboard(name: "DemoViewController", bundle: nil)
    guard let controller = sb.instantiateInitialViewController() else { return }
    controller.transitioningType = .popup
    present(controller, animated: true)
}

关闭弹框:

class DemoViewController: UIViewController {
    @IBAction func dismiss(_ sender: Any) {
        dismiss(animated: true)
    }
}
Popup.gif

总结

上述方法,可以将弹框的交互独立封装出来,具体的业务弹框只需要实现好UI和交互事件,以及相应功能即可,弹框的打开和关闭,使用presentdismiss即可。
可以看到,弹框交互和业务可以完全解耦,这也是能做到弹框的高度可定制的核心。我们可以将这个交互沉淀到基础库,用来规范项目中弹框的统一交互。

思考题

点击弹框空白区域关闭弹框,这个处理放在哪里实现更合适?欢迎留言讨论。

源码

ZCXPopup

参考

UIPresentationController
UIViewControllerAnimatedTransitioning
UIViewControllerTransitioningDelegate

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

推荐阅读更多精彩内容