Access modal view controller parent

后端 未结 6 1287
傲寒
傲寒 2021-02-01 04:05

I\'m presenting a ViewController modally. How can I access the parent view controller ?

My architecture is TabBarController=>VC1=>VC2=>VC3=>MVC1, and I want to reach VC3

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 05:04

    Here I came up with universal method to navigate from any place to root.

    1. You create a new Class file with this class, so that it's accessible from anywhere in your project:

      import UIKit
      
      class SharedControllers
      {
          static func navigateToRoot(viewController: UIViewController)
          {
              var nc = viewController.navigationController
      
              // If this is a normal view with NavigationController, then we just pop to root.
              if nc != nil
              {
                  nc?.popToRootViewControllerAnimated(true)
                  return
              }
      
              // Most likely we are in Modal view, so we will need to search for a view with NavigationController.
              let vc = viewController.presentingViewController
      
              if nc == nil
              {
                  nc = viewController.presentingViewController?.navigationController
              }
      
              if nc == nil
              {
                  nc = viewController.parentViewController?.navigationController
              }
      
              if vc is UINavigationController && nc == nil
              {
                  nc = vc as? UINavigationController
              }
      
              if nc != nil
              {
                  viewController.dismissViewControllerAnimated(false, completion:
                      {
                          nc?.popToRootViewControllerAnimated(true)
                  })
              }
          }
      }
      
    2. Usage from anywhere in your project:

      {
          ...
          SharedControllers.navigateToRoot(self)
          ...
      }
      

提交回复
热议问题