Search code examples
iosswiftuitabbarcontrolleruistoryboardsegue

Accessing child view controllers of a UITabBarController


I am new to iOS, How can I access child view controllers form UITabBarController ? Currently, I have the following.

  1. RequestTabBarController
  2. ActiveRequestsTableViewController
  3. RequestViewController

The child view controllers are connected using a Relationship Segue in the storyboard. I want to set some properties in child views from UITabBarController. How this can be accomplished.

Storyboard

storyboard_reference


Solution

  • You might define the following enum for mapping your classes:

    enum TabType:Int {
        case RequestTabBarController
        case ActiveRequestsTableViewController
        case RequestViewController
    }
    

    In such way you can have a clean access to your viewControllers:

    An array of the root view controllers displayed by the tab bar interface.

    which you can get directly from your UITabBarController, doing so:

    private weak var tabVc:UITabBarController?
    var niceObject:Whatever?
    //...//
    override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        self.tabVc = segue.destination as? UITabBarController
    
        if let vc = self.tabVc?.viewControllers?[TabType.RequestTabBarController.rawValue] as? RequestTabBarController {
            vc.doWhatEver(niceObject)
        }
    }