I need to update a variable in a View Controller and I need to do that from a Tab Bar Controller.
See image below:
I have tried so many different code but, since i implemented a Navigation Controller in between, none of them is working.
Code1
let myVC:MyViewController = self.viewControllers?[0] as MyViewController
myVC.x = "marco"
Code2
var storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var myVC:MyViewController = storyboard.instantiateViewControllerWithIdentifier("view2") as MyViewController
myVC.x = "marco"
Code3
let myInstance:MyViewController = MyViewController()
myInstance.x = "marco"
But none of them is working. Help please
Thank you very much
You need to follow the view controller hierarchy from your tab bar controller down to your custom view controller, like this:
Tab bar controller (self) -> navigation controller -> custom view controller
We want to get the tab bar controller's first view controller (a navigation controller), and then get that navigation controller's first view controller. In code, you can do it this way:
let myVC = (self.viewControllers?[0] as UINavigationController).viewControllers[0] as MyViewController
myVC.x = "marco"
Note that this is brittle, and will fail if you change the hierarchy at all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.