Search code examples
swiftuipageviewcontroller

how to setup the delegate for UIPageViewController inside Container view that is embeded in a ViewController


I have a MainViewController, that has a container view inside it that embeds a UIPageViewController. MainViewController conforms the protocols UIPageViewControllerDelegate, UIPageViewControllerDataSource and I want the embedded UIPageViewController to be delegated by the MainViewController. Is that even possible?

Basically I am trying to have a similar attitude to having a collection view inside a view controller as an outlet from storyboard, and then to setup the delegates for it (collectionView.delegate = self, assuming self delegates it) So this attitude with a UIPageViewController. The obstacle I encounter is that there is no PageView as opposode to PageViewController (comparing to collection views, I have CollectionView as opposed to CollectionViewController.

enter image description here


Solution

  • Here are the steps you could use to produce this:

    You can get a reference to your UIPageViewController by overriding func prepare(for segue: UIStoryboardSegue, sender: Any?) in MainViewController. This function is triggered when your embedded controller is made a child.

    Given you gave your segue a name (let's use pageSegue for this example), you are able to do something like this in MainViewController:

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        if segue.identifier == "pageSegue", let controller = segue.destination as? UIPageViewController {
            controller.delegate = self
            controller.dataSource = self
        }
    
    }