Swift之模态弹窗自定义二 2024-09-23 周一

简介

上一篇文章,我们讨论了UIPresentationController,实现了初步的过场动画自定义,也就是背景逐渐显示,逐渐影藏。还有就是点击蒙板退出,内容高度自定义(不是全屏)。不过用下来还有以下几个问题:
(1)加载是,从下到上的弹出很快就结束了,而背景蒙板的逐渐显示时间较长。这是因为从下到上的弹出动画还是系统默认的行为,时间较短,大约0.3秒左右。而蒙板的逐渐显示是自定义的动画行为,我设置了较长时间(3秒),想看清楚一点。
(2)退出时,更加明显,从上到下的退出很快,而背景蒙板的逐渐隐藏几乎看不到。随着系统默认动画较快地退出,containerView都被系统收回了,其子视图的动画当然消失了。

实现自定义动画

  • 现在不想要系统的从下到上的动画,而是实现从右到左的动画。

  • 统一时间长度,让视图的进场动画和背景蒙板显示动画同步。

统一参数

(1) 动画结束后,最终vc的frame需要确定,这个当做参数放入公共的代理对象中(就是那个default单例)

(2)动画的时长,几个相关的对象都要用统一的参数,这个也放在代理对象中

class TempTransitionDelegate: NSObject {
    /// 默认单例
    public static let `default`: TempTransitionDelegate = {
        LogUtil.doPrint("TempTransitionDelegate `default` 实例被创建")
        return TempTransitionDelegate()
    }()
    
    /// 设置弹窗视图的高度
    public var sheetHeight: CGFloat = 500
    let phoneWidth = UIScreen.main.bounds.width
    let phoneHeight = UIScreen.main.bounds.height
    var contentFrame: CGRect {
        CGRect(origin: CGPoint(x: 0, y: (phoneHeight - sheetHeight)), size: CGSize(width: phoneWidth, height: sheetHeight))
    }
    
    /// 设置动画时间(秒)
    public var animateDuration: TimeInterval = 3
}

自定义动画

  • 自定义对话,需要一个实现了UIViewControllerAnimatedTransitioning的对象
@MainActor public protocol UIViewControllerAnimatedTransitioning : NSObjectProtocol {

    // This is used for percent driven interactive transitions, as well as for
    // container controllers that have companion animations that might need to
    // synchronize with the main animation.
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval

    // This method can only be a no-op if the transition is interactive and not a percentDriven interactive transition.
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning)
  • 这两个函数都涉及到一个参数UIViewControllerContextTransitioning,这是动画过程中,系统给的一些有用信息
@MainActor public protocol UIViewControllerContextTransitioning : NSObjectProtocol {
    // The view in which the animated transition should take place.
    @available(iOS 2.0, *)
    var containerView: UIView { get }

    // This must be called whenever a transition completes (or is cancelled.)
    // Typically this is called by the object conforming to the
    // UIViewControllerAnimatedTransitioning protocol that was vended by the transitioning
    // delegate.  For purely interactive transitions it should be called by the
    // interaction controller. This method effectively updates internal view
    // controller state at the end of the transition.
    func completeTransition(_ didComplete: Bool)
}

    // Currently only two keys are defined by the
    // system - UITransitionContextToViewControllerKey, and
    // UITransitionContextFromViewControllerKey. 
    // Animators should not directly manipulate a view controller's views and should
    // use viewForKey: to get views instead.
    @available(iOS 2.0, *)
    func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController?

containerView可以和UIPresentationController中的一样理解,简单讲就是一个全屏的容器。
completeTransition在动画结束的时候调用一下,告诉系统过场动画结束了。
viewController比较特殊,通过from和to两个key,得到不同的VC。进场时,我们显然是需要toVC;而消失时,我们是需要fromVC。(多么脑残的人才能想出这种API?)

  • 所以,除了frame和动画时长,我们还需要一个参数isPresent来区分是载入还是退出。这两者的动画方向是不一样的。

  • 考虑了以上因素后,代码大致如下:

class TempAnimate: NSObject {
    /// 载入还是退出的标志
    public var isPresent = true
    
    /// 视图最终的frame
    public var frame: CGRect = UIScreen.main.bounds
    
    /// 动画时长
    public var duration: TimeInterval = 0.3
}

extension TempAnimate: UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        duration
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        /// 获取源视图控制器和目标视图控制器的视图
        let fromVC = transitionContext.viewController(forKey: .from)!
        let toVC = transitionContext.viewController(forKey: .to)!
  
        /// 获取容器视图,即动画发生的视图
        let containerView = transitionContext.containerView
        
        if isPresent {
            /// 进场动画从右向左进入屏幕,取toVC
            containerView.addSubview(toVC.view)
            toVC.view.frame = frame.offsetBy(dx: UIScreen.main.bounds.width, dy: 0)
            UIView.animate(withDuration: transitionDuration(using: transitionContext)) {
                toVC.view.frame = self.frame
            } completion: { _ in
                transitionContext.completeTransition(true)
            }
        } else {
            /// 退出动画从右向左离开屏幕,取fromVC
            containerView.addSubview(fromVC.view)
            fromVC.view.frame = frame
            UIView.animate(withDuration: transitionDuration(using: transitionContext)) {
                fromVC.view.frame = self.frame.offsetBy(dx: -UIScreen.main.bounds.width, dy: 0)
            } completion: { _ in
                transitionContext.completeTransition(true)
            }
        }
    }
}

在代理方法中统一传参

/// 代理方法
extension TempTransitionDelegate: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        LogUtil.doPrint("TempTransitionDelegate `animationController` forPresented 被调用")
        let animate = TempAnimate()
        animate.isPresent = true
        animate.duration = animateDuration
        animate.frame = contentFrame
        return animate
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        LogUtil.doPrint("TempTransitionDelegate `animationController` forDismissed 被调用")
        let animate = TempAnimate()
        animate.isPresent = false
        animate.duration = animateDuration
        animate.frame = contentFrame
        return animate
    }
    
    func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        LogUtil.doPrint("TempTransitionDelegate `interactionControllerForPresentation` 被调用")
        return nil
    }
    
    func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        LogUtil.doPrint("TempTransitionDelegate `interactionControllerForDismissal` 被调用")
        return nil
    }
    
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        presented.modalPresentationStyle = .custom
        LogUtil.doPrint("TempTransitionDelegate `presentationController` 被调用")
        let present = TempPresentation(presentedViewController: presented, presenting: presenting)
        present.duration = animateDuration
        present.frame = contentFrame
        return present
    }
}

大致的效果

动画同步了

同时放弃了系统从下到上的默认弹出效果,而是实现了从右到左的弹出效果,并且速度慢很多。

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

推荐阅读更多精彩内容

  • 简介 iOS系统提供的模态弹窗已经足够好用了,所以这方面一直不用操心。另外,自定义弹窗的实现方式过于复杂,很不好学...
    勇往直前888阅读 121评论 0 0
  • 在实际开发中经常会出现的效果图 : 如何实现这种效果呢? 下面直接上代码 ```objc //设置转场动画的代理 ...
    saiGo阅读 2,132评论 2 1
  • 近期在flutter开发过程中,遇到一些需要自定义转场动画的情况,就想研究一下相关的知识,有兴趣的小伙伴可以跟我一...
    percivals阅读 1,812评论 0 1
  • 1. 自定义弹框 如上图,常见的实现方式是把模态框作为一个View,需要的时候通过动画从底部弹出来。这样做起来很方...
    Dariel阅读 1,518评论 0 9
  • 最近把项目中使用到的部分组件和一些平时写的组件整理了一下,放在一个小程序中,仅供参考!文章底部有github链接。...
    杰铭的博客阅读 1,513评论 0 3