Search code examples
iosswiftuipageviewcontroller

Getting error with Page View Controller


I keep getting the following error :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The number of view controllers provided (0) doesn't match the number required (1) for the requested transition.'

I am not sure what I am doing wrong in my PageViewController that could be causing this error. Also I tried to follow the answer provided here. However, the solution didn't help me because I am not sure which piece of my code could be causing the issue. I am pretty new to Swift, so any help would be greatly appreciated.

Update: I figured out that the setViewController is causing the issue, and it goes away when deleted. However, why would that cause an issue? Thanks!

    var pageViewController: UIPageViewController!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    self.pageViewController = harishStoryboard.instantiateViewControllerWithIdentifier("ViewController1") as! UIPageViewController
    self.pageViewController.dataSource = self
    let allViewControllers = [harishStoryboard.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2, harishStoryboard.instantiateViewControllerWithIdentifier("ViewController3") as! ViewController3, harishStoryboard.instantiateViewControllerWithIdentifier("ViewController4") as! ViewController4, harishStoryboard.instantiateViewControllerWithIdentifier("ViewController5") as! ViewController5, harishStoryboard.instantiateViewControllerWithIdentifier("ViewController6") as! ViewController6, harishStoryboard.instantiateViewControllerWithIdentifier("ViewController7") as! ViewController7]
    let viewControllers = NSArray(object: allViewControllers)
    self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .Forward, animated: false, completion: nil)
    self.addChildViewController(pageViewController)
    self.view.addSubview(self.pageViewController.view)
    self.pageViewController.didMoveToParentViewController(self)
}

Solution

  • This is not how the page view controller works. You do not pass multiple view controller but only one, or max two. See the apple docs:

    When defining a page view controller interface, you can provide the content view controllers one at a time (or two at a time, depending upon the spine position and double-sided state) or as-needed using a data source. When providing content view controllers one at a time, you use the setViewControllers:direction:animated:completion: method to set the current content view controllers. To support gesture-based navigation, you must provide your view controllers using a data source object.

    I assume you want gesture bases navigation, so you will need to implement the page view controller delegate and data source. There are plenty of page view controller tutorials on google.