Search code examples
iosswiftuiviewcontrolleruitabbarcontrolleruicontainerview

Get another tab's viewcontroller variable in current tab bar - iOS - Swift


I have a tabBarController with below hierarchy

TabBarController

  • Tab 1 -> Contains Navigation Controller(NavController1) -> ViewController1 -has--> ContainerView --contains--> DisplayedViewControllerTab1 (this is my tab1 view controller displayed)

Variable dataForVC1 is in DisplayedViewControllerTab1

  • When user taps Tab3 (DisplayedViewControllerTab3), I'm trying to get value of dataForVC1 to pass to tab3 viewController

So far I've tried this

In in TabBarController - didSelect method

    var data: ModelData?  
    if let navController = tabBarController.viewControllers?[0] as? NavController1, 
       let childNavVC = navController.children.first as? ViewController1 {
       //Get container view
       let conView = childNavVC.containerView. //This is outlet

      //Looking for something like this - struck here
      if let displayedVC1 = "Container view's VC as? DisplayedViewControllerTab1 {
         data = displayedVC1.dataForVC1
     }
}

Kindly advice how to achieve this


Solution

  • You don't need to hustle around with container views. In your ViewController1 simply add references to the DisplayedViewControllerTab1 or other vc's you need and then access them directly.

    Your VC code would look something like this.

    class ViewController1: UIViewController {
       //...
       var displayedVC1: DisplayedViewControllerTab1?
       //...
    }
    
    

    And then your code now:

    var data: ModelData?  
    if let navController = tabBarController.viewControllers?[0] as? NavController1, 
       let childNavVC = navController.children.first as? ViewController1 {
         data = childNavVC.displayedVc1
    }
    

    P.S. For convenience, if you have your own TabBarController class you can add all the references you need when the controller is created or simply have computed properties, so you don't need to go deep in the hierarchy all the time.

    In your TabbarViewController class:

    var myViewController1: MyViewControllerOne? {
       return (viewControllers[0] as? NavController)?.children.first as? MyViewControllerOne
    }
    var myViewController2: MyViewControllerTwo? {
       return (viewControllers[1] as? NavController)?.children.first as? MyViewControllerTwo
    }