简体   繁体   English

Swift-从标签栏控制器更新视图控制器内的变量

[英]Swift - Update variable inside view Controller from Tab Bar Controller

I need to update a variable in a View Controller and I need to do that from a Tab Bar Controller. 我需要在View Controller中更新一个变量,并且需要在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 代码1

let myVC:MyViewController = self.viewControllers?[0] as MyViewController
myVC.x = "marco"

Code2 代码2

var storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var myVC:MyViewController = storyboard.instantiateViewControllerWithIdentifier("view2") as MyViewController
myVC.x = "marco"

Code3 代码3

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. 请注意,这很脆弱,如果您完全更改层次结构,它将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM