美文网首页
Swift 获取到当前的 UIViewController

Swift 获取到当前的 UIViewController

作者: 孤雁_南飞 | 来源:发表于2021-05-08 18:21 被阅读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
        }
    

    相关文章

      网友评论

          本文标题:Swift 获取到当前的 UIViewController

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