A. Vin A. Vin - 4 months ago 34x
Swift Question

iOS Accessing PageViewController children inside ContainerView

I have a ViewController (let's call it MainViewController) that contains a ContainerView. The ContainerView contains only one child - a PageViewController. The PageViewController pages through 4 different ViewControllers (let's call them Red, Blue, Green, and Orange ViewControllers). How would I access the various colored child ViewControllers from the MainViewController (each one contains a UITableView and I'd like to pass the data for those tableviews down from the MainActivity so that I don't have to make separate database calls to get the data from each one of the colored pages)?

Note: I know how to access a ViewController inside a ContainerView using this method: Access Container View Controller from Parent iOS . But that would only get me to the PageViewController - I need to go a level deeper than that. An answer in Swift would be greatly appreciated.

Here's a screenshot to illustrate.
enter image description here

And as a follow-on, how would I access the MainViewController from the 4 colored "grand-children" ViewControllers (correct terminology?)?


As the previous answer pointed, this is a valid way to view the children:

if let myViewControllers = myPageViewController.viewControllers as? [UIViewController] {
for viewController in myViewControllers {
    // Do something with the viewController

But it will only show the one child that is currently in view. If you want to access all the child ViewControllers, including the ones that aren't visible, when you instantiate and add them to the ContainerView/PageViewController, save a reference to them. You can then use that reference to access any function/data inside of each child ViewController.