美文网首页
Swift之模态弹窗自定义二 2024-09-23 周一

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

作者: 松哥888 | 来源:发表于2024-09-22 22:08 被阅读0次

简介

上一篇文章,我们讨论了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
    }
}

大致的效果

动画同步了

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

相关文章

网友评论

      本文标题:Swift之模态弹窗自定义二 2024-09-23 周一

      本文链接:https://www.haomeiwen.com/subject/fmsxrjtx.html