Pass data from View Controller to Child Controller in Swift

為{幸葍}努か 提交于 2019-11-30 20:37:40
Laffen

When loading the ParentViewController from your ViewController, there are no views loaded into memory. It's just an instance of your ParentViewController class.

override func viewDidLoad() {
   var pVC = ParentViewController()
   pVC.a = a
}

And i guess you are loading or presenting this controller somewhere else in your code. If so, it makes sense that you're successfully printing the variable being set.

println(a) -> "Test"

However, when you are instantiating your ChildViewController, you are providing a frame for its convenience init and you are actually initiating the view hierarchy, which in turn fires the viewDidLoad event. This is executed before the a variable is being set from ParentViewController -> ViewDidLoad. And your result from printing the a variable is actually an empty string.

One option is to put your logic within their own functions that you explicitly call. Optionally with your data as parameters or you set the variables before calling the function(s).

You should check out some of these to get a better understanding of how things work and paths you can follow to accomplish what you want.

Instantiate and Present a viewController in Swift

UIViewController class reference

How can I passing data from parent view controller to child view controller?

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!