0

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.

Akhil Varma
  • 3
  • 1
  • 5

2 Answers2

3

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?

Community
  • 1
  • 1
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • Wow thank you this suited my needs. Would love an explanation of the `viewWillAppear` and how the variable values can be accessed through encapsulation – Sami Nov 24 '16 at 00:17
  • In viewWillAppear, first object is extracted from the array of view controllers of a tabBarController. Since this object is of type Tab1ViewController, so it is casted to Tab1ViewController so that we can access it's outlet - testTextField – PGDev Nov 24 '16 at 03:01
  • @PGDev do you have an idea of how to transfer data if the child view controllers are embedded in a navigation view controller? – Akhil Varma Dec 06 '16 at 09:55
0

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.

Nick Kohrn
  • 5,779
  • 3
  • 29
  • 49