Swift 获取到当前的 UIViewController

2021-05-08  本文已影响0人  孤雁_南飞

获取当前所在的 UIView

    //获取所在的 UIView
    func getUpView() -> UIView? {
        let window = UIApplication.shared.keyWindow!
        let fontView = window.subviews.last
        
        return fontView
    }

获取最上层的 uiviewcontroller

    //获取最上层的 uiviewcontroller
    func getUpVC() -> UIViewController? {
        let rootVC = UIApplication.shared.keyWindow?.rootViewController
        let currentVC = getCurrentVC(from: rootVC)
        return currentVC
    }
    func getCurrentVC(from rootVC: UIViewController?) -> UIViewController? {
        var rootVC = rootVC
        var currentVC: UIViewController?
        if rootVC?.presentedViewController != nil {
            // 视图是被presented出来的
            rootVC = rootVC?.presentedViewController
        }
        if rootVC is UITabBarController {
            let tabBar = rootVC as! UITabBarController
            currentVC = getCurrentVC(from: tabBar.selectedViewController)
        } else if rootVC is UINavigationController {
            let nav = rootVC as! UINavigationController
            currentVC = getCurrentVC(from: nav.visibleViewController)
        } else {
            currentVC = rootVC
        }
        return currentVC
    }
上一篇下一篇

猜你喜欢

热点阅读