首页 > 解决方案 > 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.

标签: swiftxcode

解决方案


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")
            }
        }
    }
}

推荐阅读