Akhil Varma Akhil Varma - 23 days ago 8
Swift Question

Data transfer between child tabs in a Tab bar controller

My Tab bar controller has 4 tabs, I have 6 textfields in VC1 and want to use the data entered to display labels in VC2, VC3 & VC4. I have read about adding data to TabBarController subclass and using it in the rest of VC's but stuck on implementation. I'm an absolute beginner and any code or links to the implementation of the code will be great.

Answer

Try this:

I have created a UITabBarController with 2 child controllers Tab1ViewController and Tab2ViewController.

Screenshot of storyboard:

enter image description here

Code:

class Tab1ViewController: UIViewController
{
    @IBOutlet weak var testTextField: UITextField!
    override func viewDidLoad()
    {
        super.viewDidLoad()
    }
}

class Tab2ViewController: UIViewController
{
    @IBOutlet weak var testLabel: UILabel!
    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        let tab1Controller = self.tabBarController?.viewControllers?.first as! Tab1ViewController
        self.testLabel.text = tab1Controller.testTextField.text
    }
}

Similarly you can create 4 tabs and other textfields.

For more refer to : How do I pass data from a tab bar controller to one of its tabs?