Get the current view controller from the app delegate

前端 未结 11 1983
悲哀的现实
悲哀的现实 2020-11-30 22:46

i am new to ios. I need to know the current view controller from app delegate.. i have no idea about this and i don\'t knowto implement this. i am using this code toimplemn

11条回答
  •  佛祖请我去吃肉
    2020-11-30 23:03

    Here're some class/static functions in swift that I keep in a Utility class and can help you:

    // Returns the most recently presented UIViewController (visible)
    class func getCurrentViewController() -> UIViewController? {
    
        // If the root view is a navigation controller, we can just return the visible ViewController
        if let navigationController = getNavigationController() {
    
            return navigationController.visibleViewController
        }
    
        // Otherwise, we must get the root UIViewController and iterate through presented views
        if let rootController = UIApplication.shared.keyWindow?.rootViewController {
    
            var currentController: UIViewController! = rootController
    
            // Each ViewController keeps track of the view it has presented, so we
            // can move from the head to the tail, which will always be the current view
            while( currentController.presentedViewController != nil ) {
    
                currentController = currentController.presentedViewController
            }
            return currentController
        }
        return nil
    }
    
    // Returns the navigation controller if it exists
    class func getNavigationController() -> UINavigationController? {
    
        if let navigationController = UIApplication.shared.keyWindow?.rootViewController  {
    
            return navigationController as? UINavigationController
        }
        return nil
    }
    

提交回复
热议问题