How to access the child view controller from parent view controller in swift?

Viewed 1737

I have a view controller which has a child view controller and I want to access that child view controller from its parent view controller.

How can I achieve that?

2 Answers

The answer is ... (drum-roll......) ... it depends.. :-)

NSViewController & UIViewController have a .parent property. https://developer.apple.com/documentation/uikit/uiviewcontroller/1621362-parent https://developer.apple.com/documentation/appkit/nsviewcontroller/1434491-parent

However, it is only populated if you're implementing the container-view-controller design pattern: https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html (many uikit components use this pattern) IE:

aViewController.addChild(bViewController)
bViewControler.didMove(toParent: aViewController)
bViewController.parent // is aViewController

*Note: you'll have to manage the view stack yourself, this just ensures things like the lifecycle/drawing/resize/etc handlers happen in the correct order

If you need to retain a reference to a view controller (child or otherwise), create a property on the child and set a reference to it, or use the container-view-controller design, it's very useful.

Cheers
- J

There are many ways but for simply explanation I think this example will be instructive for you.

Suppose that you are trying to achieve navigate your viewcontrollers and using navigation controller for that in a stack

   let parentVC = UIViewController()
   let childVC = UIViewController()

   parentVC.navigationController?.viewControllers.append(childVC)
   let childVCisHere = parentVC.navigationController?.viewControllers.first

Finally think about the analogy I established on - GodFather - family hieararchy

Don Vito Corleone, he is the boss also father of the family parentVC

Sonny Corleone, he is dealing with dirty jobs, navigate childs behalf of family navigationController

Michael Corleone, he is little bro, people see him on the screen mostly :) childVC

Related