How to Turn Pages Programmatically in UIPageViewController

Written by

in

Quick answer: Call setViewControllers(_:direction:animated:completion:) with a one-element array holding the page you want to show. That call bypasses your data source, so update your own current-index property at the same time or the next swipe will land on the wrong page.

Why this happens

UIPageViewController has no nextPage() or goToPage(_:) method. The only supported way to change pages from code is the same method you use to install the very first page:

setViewControllers(_:direction:animated:completion:)

It takes an array of view controllers because a page view controller can display two pages at once when it has a spine — the iBooks-style double-page layout. If you show one page at a time, you pass a one-element array and the extra capacity is simply unused.

The important part is what this call does not do: it never asks your data source for anything. pageViewController(_:viewControllerBefore:) and pageViewController(_:viewControllerAfter:) are only consulted while the user is swiping. So if you jump to page 7 in code but leave your stored index at 2, the next gesture asks the data source for the neighbours of page 2 and the reader snaps backwards — or, if the index is out of range, you get a blank page.

How to fix it

1. Call setViewControllers with the target page

Build or fetch the view controller for the page you want, pick a direction, and hand it over in an array.

import UIKit

final class BookViewController: UIPageViewController {
    private var currentIndex = 0
    private let pageCount = 10

    func go(to index: Int, animated: Bool = true) {
        guard index >= 0, index < pageCount, index != currentIndex else { return }

        guard let target = storyboard?.instantiateViewController(
            withIdentifier: "PageContentViewController"
        ) as? PageContentViewController else { return }
        target.pageIndex = index

        let direction: UIPageViewController.NavigationDirection =
            index > currentIndex ? .forward : .reverse

        currentIndex = index
        setViewControllers([target], direction: direction, animated: animated, completion: nil)
    }
}

The direction is cosmetic. It decides which way the curl or scroll animates, not which page you land on. Passing .forward with a lower index still shows that lower page, just with a forward-looking animation — which is why it pays to compute it from the index comparison rather than hard-coding it.

The completion closure receives a Bool telling you whether the animation finished. You rarely need it, but it is the right place to chain a second call if you are stepping through several pages.

2. Keep the data source in sync

Derive the neighbouring page from the view controller that is passed in, not from a shared property. That way the data source stays correct no matter how the page was changed.

extension BookViewController: UIPageViewControllerDataSource {
    func pageViewController(_ pageViewController: UIPageViewController,
                            viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard let page = viewController as? PageContentViewController else { return nil }
        return makePage(at: page.pageIndex - 1)
    }

    func pageViewController(_ pageViewController: UIPageViewController,
                            viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let page = viewController as? PageContentViewController else { return nil }
        return makePage(at: page.pageIndex + 1)
    }

    private func makePage(at index: Int) -> PageContentViewController? {
        guard index >= 0, index < pageCount else { return nil }
        guard let page = storyboard?.instantiateViewController(
            withIdentifier: "PageContentViewController"
        ) as? PageContentViewController else { return nil }
        page.pageIndex = index
        return page
    }
}

Returning nil at the first and last page is what stops the reader from swiping past the ends.

3. Update your index yourself — the delegate will not fire

pageViewController(_:didFinishAnimating:previousViewControllers:transitionCompleted:) is called only for user-driven swipes. A programmatic setViewControllers call does not trigger it, so you must set currentIndex yourself, as in step 1. If you rely on the delegate to track position, the first programmatic jump leaves your index stale and the next swipe misbehaves.

4. Two-page (spine) layouts

If spineLocation is .mid, the page view controller shows two pages at a time and expects two view controllers in left-to-right order for a forward turn:

setViewControllers([leftPage, rightPage], direction: .forward, animated: true, completion: nil)

Passing a single controller in that configuration leaves half the spread empty.

5. Jumping more than one page

The animation is always a single page turn, no matter how far the index moves. For a large jump, pass animated: false:

setViewControllers([pages[0]], direction: .reverse, animated: false, completion: nil)

This is also the right choice when restoring saved reading position at launch or after a rotation, where an animation would look like a glitch.

One more caution: avoid calling setViewControllers from inside a delegate callback while a gesture transition is still running. Queue it on the main queue behind your own “transition in progress” flag, otherwise the two animations fight and you can end up on an unexpected page.

How to prevent it

  • Keep one source of truth for the current index and update it on both the gesture path and the programmatic path.
  • Derive page indices from the view controller instance handed to the data source, not from a shared mutable property.
  • Guard the index against your model’s bounds before calling setViewControllers.
  • Use animated: false when restoring state on launch or after a layout change.
  • Test the sequence swipe → programmatic jump → swipe; that is where stale indices surface.

FAQ

Does setViewControllers call my data source?

No. The data source is only asked for neighbouring pages during user gestures. You are responsible for supplying the target view controller and for keeping your own index current.

Why does the page go blank after a programmatic jump?

Usually the data source is still answering from an old index, or the target view controller was created without its content assigned. Check that the index you set on the new controller matches your model, and that the data source returns nil only at the real boundaries.

Can I animate a jump from page 1 to page 8?

Not as one multi-page animation. setViewControllers animates a single turn; use animated: false for an instant jump, or chain single-page calls in the completion handler if you want the reader to see the pages go by.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.