首页 > 解决方案 > 在场景委托中作为背景之前获取对最后一次看到的 VC 的引用

问题描述

我有一个rootViewControlleras UITableViewController,当一个单元格被点击时,它会呈现一个模态 VC。在那些 VC 中,我正在制作动画,UIViewPropertyAnimator问题是当应用程序在当前显示该 VC 的同时被发送到后台时,因为动画师没有正确停止并且我viewWillDissapear没有在我停止动画师的地方被调用。

如果我想获得对我的 rootVC 的引用,这很容易,window.rootViewController但是模态 VC 呢?

标签: iosswift

解决方案


我假设您的modal VCIS 是TOPMOST屏幕,我认为它应该是您想要从中获得参考的最顶层屏幕。

如果是这样,那里有很多参考资料。但这是我上次需要它时使用的整个功能。

var windowScene: UIScene? = {
    let windowScene = UIApplication.shared
    .connectedScenes
    .filter { $0.activationState == .foregroundActive }
    .first
    return windowScene
}()

var windowRootController: UIViewController? {
    if let window = windowScene as? UIWindowScene {
        return window.windows.last?.rootViewController
    }

    return UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
}

/// Category for any controller.
extension UIViewController {
    /// Class function to get the current or top most screen.
    class func current(controller: UIViewController? = windowRootController) -> UIViewController? {
        guard let controller = controller else { return nil }

        if let navigationController = controller as? UINavigationController {
            return current(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return current(controller: selected)
            }
        }
        if let presented = controller.presentedViewController {
            return current(controller: presented)
        }
        return controller
    }
}

所以基本上,就像这样称呼它let modalVC = UIViewController.current()

玩这段代码,就像我很确定你不需要windowSceneand一样windowRootViewController,但不是 100% 确定。试试看。希望能帮助到你!


推荐阅读