idealisticDreamer2.0 idealisticDreamer2.0 - 3 months ago 14
iOS Question

How to pass content of UITextField to another UITableViewController linked by UITabbarController

i am new to iOS development in swift 3 and i am encountering some trouble.
Like in the picture below i have 2 UITableViewControllers with a textfield in the first one . The two tableViews are linked by a tabbarController And i would like to recover the content of the textfield to use it in the secondTableViewController.
I dont know how to do it, the most common tutorials about data passing explain with a button action but i would like to recover simply the data in changing the tableView if it is possible.

I hope i was clear in my question.


Answer

Let's assume you have a tabbar based project where two view controller FirstVC and SecondVC are there. In the firstVC you have a textField, and you want that textFiled to use in SecondVC. You can pass the textFields in the shouldSelectViewController delegate method. So here is the FirstVC should look like

class FirstViewController: UIViewController,UITabBarControllerDelegate {

    @IBOutlet weak var txtFldFirst: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.tabBarController?.delegate = self;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool
    {
        NSLog("view controller descriptionn should select = %@", viewController.description);
        let selectedVC:SecondViewController = viewController as! SecondViewController
        selectedVC.txtFld = self.txtFldFirst


        return true;
    }

And SecondVC should look like this

class SecondViewController: UIViewController {

    var txtFld : UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        NSLog("text fld = %@", txtFld.text);
    }

Output would be the text of textField present in FirstVC.

Happy coding ...

Comments