Get top most UIViewController

后端 未结 24 1907
别那么骄傲
别那么骄傲 2020-11-22 14:47

I can\'t seem to get the top most UIViewController without access to a UINavigationController. Here is what I have so far:

UIApplic         


        
24条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 15:24

    The best solution for me is an extension with a function. Create a swift file with this extension

    First is the UIWindow extension:

    public extension UIWindow {
        var visibleViewController: UIViewController? {
            return UIWindow.visibleVC(vc: self.rootViewController)
        }
    
        static func visibleVC(vc: UIViewController?) -> UIViewController? {
            if let navigationViewController = vc as? UINavigationController {
                return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
            } else if let tabBarVC = vc as? UITabBarController {
                return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
            } else {
                if let presentedVC = vc?.presentedViewController {
                    return UIWindow.visibleVC(vc: presentedVC)
                } else {
                    return vc
                }
            }
        }
    }
    

    inside that file add function

    func visibleViewController() -> UIViewController? {
        let appDelegate = UIApplication.shared.delegate
        if let window = appDelegate!.window {
            return window?.visibleViewController
        }
        return nil
    }
    

    And if you want to use it, you can call it anywhere. Example:

      override func viewDidLoad() {
        super.viewDidLoad()
          if let topVC = visibleViewController() {
                 //show some label or text field 
        }
    }
    

    File code is like this:

    import UIKit
    
    public extension UIWindow {
        var visibleViewController: UIViewController? {
            return UIWindow.visibleVC(vc: self.rootViewController)
        }
    
        static func visibleVC(vc: UIViewController?) -> UIViewController? {
            if let navigationViewController = vc as? UINavigationController {
                return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
            } else if let tabBarVC = vc as? UITabBarController {
                return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
            } else {
                if let presentedVC = vc?.presentedViewController {
                    return UIWindow.visibleVC(vc: presentedVC)
                } else {
                    return vc
                }
            }
        }
    }
    
    func visibleViewController() -> UIViewController? {
        let appDelegate = UIApplication.shared.delegate
        if let window = appDelegate!.window {
            return window?.visibleViewController
        }
        return nil
    }
    

提交回复
热议问题