How can I pass data between ViewControllers by using a UIPageViewController

Hi everyone,

I have 3 ViewControllers within i can swipe by using a PageViewController.

That works fine. But now i want to pass data from the first VC to the second one.

Is it possible, and how I can do this?


Thanks in advance,

Guenny

Replies

The UIPageViewControllerDataSource methods pageViewController(_:viewControllerAfter:) and pageViewController(_:viewControllerBefore:) are provided with the current content view controller and return the optional next content view controller, so data can be passed in there.

did you know how to do it please ?!

Hi,


I had some difficulty finding a solution to this and came up with something myself using delegation.


In the ViewController sending the data, define a delegate as follows:

protocol FirstVCDelegate {
     func foo(someData: String)
}
class FirstViewController: UIViewController {
     var delegate: FirstVCDelegate?

....

     func someMethod() {
          delegate?.foo("first VC")
     }

}


In the PageViewController set up your View Controllers as follows:

class PageViewController: UIPageViewController, ... {
     var myViewControllers = [UIViewController]()

override func viewDidLoad() {
     let firstVC = storyboard?.instantiateViewController(withIdentifier: "FirstViewController") as! FirstViewController
     let secondVC = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController

     firstVC.delegate = secondVC

     myViewControllers.append(firstVC)
     myViewControllers.append(secondVC)

}

     // MARK: - PageVC Delegate / Datasource


and finally, the receiving ViewController implements the delegate as follows:

class SecondViewController: UIViewController, FirstVCDelegate {
     
     ....

     func foo(data: String) { // This method is triggered from FirstViewController's delegate?.foo("first VC")
          print(data)  // "first VC" will be printed
     }
}


Good luck,

Aaron