Get the instance of another view controller in the same tab bar

My tab bar has 3 tabs. If I’m on the view controller of tab 1 first and then sometime later in the app I end up in tab 2, how do I get the instance of tab 1 (in code) that is currently loaded? The view controller’s viewDidLoad function only gets called once so as long as I visited a tab, it’s view controller is still somewhere.

Is it possible to get a reference to an instance of another view controller in a tab bar controller? I don’t want to instantiate a new view controller, I want the current instance that has been loaded.

Add Comment
2 Answer(s)

Yes, it is possible. You can get it’s instance by providing the index of the UIViewController you want to the viewCotnrollers property in the UITabBarController.

class MyTabBarController: UITabBarController {      override func viewDidLoad() {         super.viewDidLoad()         // after loading is done         let firstViewController = viewControllers?[0]         print(firstViewController?.title)     } } 

If you’re trying to get the firstViewController from the secondViewController which is embedded inside the UINavigationController use this:

class SecondController: UIViewController {      override func viewDidLoad() {         super.viewDidLoad()         // after loading is done         let firstViewController = navigationController?.tabBarController?.viewControllers?[0]         print(firstViewController?.title)     } } 

And here’s the extended version in case you’re not sure:

class SecondController: UIViewController {      override func viewDidLoad() {         super.viewDidLoad()         // after loading is done         if let navigationController = navigationController {             if let tabBarController = navigationController.tabBarController {                 let firstViewController = tabBarController.viewControllers?[0]                 print(firstViewController?.title)             } else {                 print("I'm not embedded in a tabBar controller")             }         } else {             print("I'm not embedded in a navigation controller")             if let tabBarController = tabBarController {                 let firstViewController = tabBarController.viewControllers?[0]                 print(firstViewController?.title)             } else {                 print("I'm not embedded in a tabBar controller")             }         }     } } 
Answered on August 4, 2020.
Add Comment

If you are inside a vc in tab 2 for example, you can get viewController from tab 1 like this:

if let firstTabVc = tabBarController?.viewControllers.first {    //you have vc here } 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.