1

I'm trying to pass data from my main ViewController to another ViewController in a Tab Bar.

enter image description here

I have tried using the following code , and got an error Could not cast value of type 'Test.FirstViewController' to 'Test.ViewController'

override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let tab1Controller = self.tabBarController?.viewControllers?.first as! ViewController print(tab1Controller.test) } 
1
  • @matt if I set it to as! FirstViewController then I won't have access to the variables in ViewController, the point is I want to pass data from ViewController to the view controller of the tab bar. Commented Nov 5, 2017 at 11:10

3 Answers 3

3

I just used the following code which just worked fine for me on Xcode 9 with swift 4.0. The following method is declared in the View Controller class which just presents the First View Controller.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "sendingToTabBar" { let storyboard = UIStoryboard(name: "Main", bundle: nil) let tabVC = storyboard.instantiateViewController(withIdentifier: "tabVC") as! UITabBarController self.present(tabVC, animated: true, completion: { let vc = tabVC.selectedViewController as! FirstViewController vc.dataLBL.text = self.dataTF.text! }) } } 
Sign up to request clarification or add additional context in comments.

Comments

2

You can access the tab bar controllers in your ViewController prepare method and set your values.

Prepare for segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let barViewControllers = segue.destination as! UITabBarController let destinationViewController = barViewControllers.viewControllers?[0] as! FirstViewController destinationViewController.test = "Hello TabBar 1" // access the second tab bar let secondDes = barViewControllers.viewControllers?[1] as! SecondViewController secondDes.test = "Hello TabBar 2" } 

Then in your tab bar ViewControllers declare variables, you want to set the values to.

@IBOutlet weak var label: UILabel! var test: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. label.text = test } 

FirstViewController

enter image description here

SecondViewController

enter image description here

Comments

-1

You could do a number of things, what I would do is to just make a global variable so that both view controllers can access it. Another option is to give each view controller a separate global variable, and when the view is loaded, the variable is set to self, then make a variable that can be set by the other view controller.

example:

var data:Any? viewDidLoad() { viewControllerA = self } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.