Resolved: Disable UIPageViewController Scroll

In this post, we will see how to resolve Disable UIPageViewController Scroll

Question:

I have UIPageViewController with 3 child viewControllers. Is it possible to disable/prevent a user from scrolling to one specific viewController (i.e. User can scroll from view controller B to A, but cannot from B to C – until I later toggle permission allowing user to go from B to C).
Any guidance would be greatly appreciated!
I’ve been able to disable the scroll via UIPageViewController scrollView, but can’t isolate disabling to a specific viewController.
I’ve also tried putting a check in UIPageViewController delegate functions viewControllerBefore and viewControllerAfter where I would return nil if the user tried scrolling from B to C, but it seems like doing so also returns nil for viewController A…
}

Best Answer:

One approach – which, I think, is pretty straight-forward and would be a reasonable solution…
Add a maxPages property to your page view controller. Then, in viewControllerAfter, do this:
Start maxPages at 2, then in the class that is controlling your page view controller, when you want to allow the user to go to the 3rd page, change the maxPages property to 3.
Here is a quick example…
We’ll start with a simple “page” view controller – a label centered vertically:
Then, a view controller to hold our page view controller, along with a switch to Allow/Not-Allow scrolling to the 3rd page:
and our custom Page View Controller:
It will look like this:
enter image description here enter image description here
Arrays are zero-based, so we’ve set the labels to match the array index.
When the switch is Off, we can only scroll back-and-forth between Page 0 and Page 1.
When the switch is On, we can scroll on to the 3rd page – Page 2:
enter image description here
Notice that we have a little bit of code inside the didSet {} block of our maxPages var. When we set maxPages to a new value, we need to “re-set” the view controllers array of our Page View Controller, while keeping the current page visible.

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com