Is it possible to Turn page programmatically in UIPageViewController?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
UIPageViewController is a powerful component in iOS that allows developers to implement paginated navigation through views. It’s particularly useful for creating onboarding screens, e-book readers, or any feature that requires linear navigation. One common question that arises when using UIPageViewController is whether it is possible to programmatically turn to a specific page. In this article, we'll explore how to do just that, delving into the technical details to provide a comprehensive understanding.
Understanding UIPageViewController
UIPageViewController provides a way to manage page navigation in iOS apps. It handles swipes between pages seamlessly, offering both horizontal and vertical transitions. There are two different navigation styles available:
- Page Curl: Mimics the turning of a page in a physical book.
- Scroll: Allows for a more modern scrolling effect.
To programmatically navigate to a particular page, the navigation style must be set to `.scroll` as `.pageCurl` may limit direct manipulations.
Programmatically Turning Pages
To move to a specific page programmatically, you need to consider the following steps:
- Setup Data Source: The data source of a `UIPageViewController` is responsible for providing view controllers on demand.
- Use `setViewControllers` Method: This method allows you to change the currently visible view controllers.
Here's an example of turning to a specific page programmatically:
- We initialize a UIPageViewController with some pages, each represented by a simple UIViewController with different background colors.
- The `navigateToPage` function allows us to jump to any page by its index using `setViewControllers`. This function takes three arguments:
- The view controllers you want to show.
- The direction of the transition (`.forward` or `.reverse`).
- A completion handler that runs after the page is set.
- Data Source and Delegate: Make sure you’ve assigned `dataSource` and `delegate` to manage the navigation and handle events.
- Index Bounds: When programmatically changing pages, always check that the index is within bounds to prevent crashes.
- Animation Impact: Frequent animated transitions might lead to performance issues, so use animation judiciously.

