美文网首页
AJGetTopViewControllerTool

AJGetTopViewControllerTool

作者: 古月思吉 | 来源:发表于2017-11-28 15:04 被阅读0次

    如何获取当前屏幕中显示的viewController?
    AJGetTopViewControllerTool.swift 文件定义:

    import UIKit
    
    class AJGetTopViewControllerTool: NSObject {
    
        @objc class func topViewController() -> UIViewController? {
            return self.topViewControllerWithRootViewController(viewController: self.getCurrentWindow()?.rootViewController)
        }
        
        @objc class func topViewControllerWithRootViewController(viewController :UIViewController?) -> UIViewController? {
            
            if viewController == nil {
                return nil
            }
            
            if viewController?.presentedViewController != nil {
                /* 递归找最上面的viewController */
                return self.topViewControllerWithRootViewController(viewController: viewController?.presentedViewController!)
            }
            else if viewController?.isKind(of: UITabBarController.self) == true {
                return self.topViewControllerWithRootViewController(viewController: (viewController as! UITabBarController).selectedViewController)
            }
            else if viewController?.isKind(of: UINavigationController.self) == true {
                return self.topViewControllerWithRootViewController(viewController: (viewController as! UINavigationController).visibleViewController)
            }
            else {
                return viewController
            }
            
        }
        
        // 找到当前显示的window
        class func getCurrentWindow() -> UIWindow? {
            // 找到当前显示的UIWindow
            var window: UIWindow? = UIApplication.shared.keyWindow
            /**
             window有一个属性:windowLevel
             当 windowLevel == UIWindowLevelNormal 的时候,表示这个window是当前屏幕正在显示的window
             */
            if window?.windowLevel != UIWindowLevelNormal {
                for tempWindow in UIApplication.shared.windows {
                    if tempWindow.windowLevel == UIWindowLevelNormal {
                        window = tempWindow
                        break
                    }
                }
            }
            return window
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:AJGetTopViewControllerTool

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