Akhil Varma
Akhil Varma

Reputation: 3

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.

Upvotes: 0

Views: 1527

Answers (2)

Nick Kohrn
Nick Kohrn

Reputation: 6049

You can use NotificationCenter to notify anything in your application about changes. For instance, you can make a view controller listen for changes that occur when the text property of your UITextField changes, and then you can perform an action in that view controller.

For example, if you have six text fields in your first view controller, you can make the last view controller listen for the notification that is posted when the text property changes in the text field in the first view controller. Then, your last view controller can do whatever you need it to do when it detects the change.

Here is a tutorial that explains this very nicely.

Upvotes: 0

PGDev
PGDev

Reputation: 24341

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?

Upvotes: 4

Related Questions