How to pass data from XIB ViewController to TabBarController in iOS Swift

Viewed 27

I have been trying to pass data from XIB viewController to XIB TabBarController but screen are moved but data are not passed successfully.

Here is code for passing data from viewController to TabBarController

                let cont = MyTabsViewController()
                cont.data1 = data1
                cont.data2 = data2
                cont.data3 = data3
                cont.data4 = data4
                cont.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                let nav = UINavigationController(rootViewController: self)
                UIApplication.shared.keyWindow?.rootViewController = nav
                nav.pushViewController(cont, animated: true)
1 Answers

So, here you can come -

  1. Either use self.tabBarController, here is self is Child ViewController which is inside TabBarViewController, you will get the reference of nearest TabBarController

  2. If You are using some third-party TabBarController, then you can keep a closure inside Child ViewController, which will be called when you want to set Data in Tabbar.

    // Set in Child VC
    var setDataHandler: ((_ data1: String, data2: String) -> Void)?
    
    // Set in TabBar while Setting Child VC
    vc.setDataHandler = (data1: String, data2: String) {
     //TODO: Update Your TabBar State
    }
    
    // In Child VC, when you want to call Tabbar
    self.setDataHandler("AA", "BB")
    
Related