Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Recipe: Page View Controllers

This UIPageViewController class builds a book-like interface that uses individual view controllers as its pages. Users swipe from one page to the next or tap the edges to move to the next or previous page. All a controller's pages can be laid out in a similar fashion, such as in Figure 5-5, or each page can provide a unique user interaction experience. Apple precooked all the animation and gesture handling into the class for you. You provide the content, implementing delegate and data source callbacks.

Figure 5-5

Figure 5-5 The UIPageViewController class creates virtual "books" from individual view controllers.

Book Properties

Your code customizes a page view controller's look and behavior. Its key properties specify how many pages are seen at once, the content used for the reverse side of each page, and more. Here's a rundown of those properties:

  1. The controller's doubleSided property determines whether content appears on both sides of a page, as shown in Figure 5-5, or just one side. Reserve the double-sided presentation for side-by-side layout when showing two pages at once. If you don't, you'll end up making half your pages inaccessible. The controllers on the "back" of the pages will never move into the primary viewing space. The book layout is controlled by the book's spine.
  2. The spineLocation property can be set at the left or right, top or bottom, or center of the page. The three spine constants are UIPageViewControllerSpineLocationMin, corresponding to top or left, UIPageViewControllerSpineLocationMax for the right or bottom, and UIPageViewControllerSpineLocationMid for the center. The first two of these produce single-page presentations; the last with its middle spine is used for two-page layouts. Return one of these choices from the pageViewController:spineLocationForInterfaceOrientation: delegate method, which is called whenever the device reorients, to let the controller update its views to match the current device orientation.
  3. Set the navigationOrientation property to specify whether the spine goes left/right or top/bottom. Use either UIPageViewControllerNavigationOrientationHorizontal (left/right) or UIPageViewControllerNavigationOrientationVertical (top/bottom). For a vertical book, the pages flip up and down, rather than employing the left and right flips normally used.
  4. The transitionStyle property controls how one view controller transitions to the next. At the time of writing, the only transition style supported by the page view controller is the page curl, UIPageViewControllerTransitionStylePageCurl.

Wrapping the Implementation

Like table views, page view controllers use a delegate and data source to set the behavior and contents of its presentation. Unlike with table views, I have found that it's simplest to wrap these items into a custom class to hide their details from my applications. I find the code needed to support a page view implementation rather quirky—but highly reusable. A wrapper lets you turn your attention away from fussy coding details to specific content-handling concerns.

In the standard implementation, the data source is responsible for providing page controllers on demand. It returns the next and previous view controller in relationship to a given one. The delegate handles reorientation events and animation callbacks, setting the page view controller's controller array, which always consists of either one or two controllers, depending on the view layout. As Recipe 5-5 demonstrates, it's a bit of a mess to implement.

Recipe 5-5 creates a BookController class. This class numbers each page, hiding the next/previous implementation details and handling all reorientation events. A custom delegate protocol (BookDelegate) becomes responsible for returning a controller for a given page number when sent the viewControllerForPage: message. This simplifies implementation so the calling app only has to handle a single method, which it can do by building controllers by hand or by pulling them from a storyboard.

To use the class defined in Recipe 5-5, you must establish the controller, add it as a subview, and declare it as a child view controller, ensuring it receives orientation and memory events. Here's what that code might look like. Notice how the new controller is added as a child to the parent, and its initial page number set:

// Establish the page view controller
bookController = [BookController bookWithDelegate:self];
bookController.view.frame = (CGRect){.size = appRect.size};

// Add the child controller, and set it to the first page
[self.view addSubview:bookController.view];
[self addChildViewController:bookController];
[bookController didMoveToParentViewController:self];
[bookController moveToPage:0];

Exploring the Recipe

Recipe 5-5 handles its delegate and data source duties by tagging each view controller's view with a number. It uses this number to know exactly which page is presented at any time and to delegate another class, the BookDelegate, to produce a view controller by index.

The page controller itself always stores zero, one, or two pages in its view controller array. Zero pages means the controller has not yet been properly set up. One page is used for spine locations on the edge of the screen; two pages for a central spine. If the page count does not exactly match the spine setup, you will encounter a rather nasty runtime crash.

The controllers stored in those pages are produced by the two data source methods, which implement the before and after callbacks. In the page controller's native implementation, controllers are defined strictly by their relationship to each other, not by an index. This recipe replaces those relationships with a simple number, asking its delegate for the page at a given index.

Here, the useSideBySide: method decides where to place the spine, and thus how many controllers show at once. This implementation sets landscape as side-by-side and portrait as one-page. You may want to change this for your applications. For example, you might use only one page on the iPhone, regardless of orientation, to enhance text readability.

Recipe 5-5 allows both user- and application-based page control. Users can swipe and tap to new pages or the application can send a moveToPage: request. This allows you to add external controls in addition to the page view controller's gesture recognizers.

The direction that the page turns is set by comparing the new page number against the old. This recipe uses a Western-style page turn, where higher numbers are to the right and pages flip to the left. You may want to adjust this as needed for countries in the Middle and Far East.

This recipe, as shown here, continually stores the current page to system defaults, so it can be recovered when the application is relaunched. It will also notify its delegate when the user has turned to a given page, which is useful if you add a page slider, as is demonstrated in Recipe 5-6.

Recipe 5-5. Creating a Page View Controller Wrapper

// Define a custom delegate protocol for this wrapper class
@protocol BookControllerDelegate <NSObject>
- (id) viewControllerForPage: (int) pageNumber;
- (void) bookControllerDidTurnToPage: (NSNumber *) pageNumber;

// A Book Controller wraps the Page View Controller
@interface BookController : UIPageViewController
    <UIPageViewControllerDelegate, UIPageViewControllerDataSource>
+ (id) bookWithDelegate: (id) theDelegate;
+ (id) rotatableViewController;
- (void) moveToPage: (uint) requestedPage;
- (int) currentPage;

@property (nonatomic, weak) id <BookControllerDelegate> bookDelegate;
@property (nonatomic, assign) uint pageNumber;

#pragma Book Controller
@implementation BookController
@synthesize bookDelegate, pageNumber;

#pragma mark Utility
// Page controllers are numbered using tags
- (int) currentPage
    int pageCheck = ((UIViewController *)[self.viewControllers
    return pageCheck;

#pragma mark Page Handling
// Update if you'd rather use some other decision style
- (BOOL) useSideBySide: (UIInterfaceOrientation) orientation
    BOOL isLandscape = UIInterfaceOrientationIsLandscape(orientation);
    return isLandscape;

// Update the current page, set defaults, call the delegate
- (void) updatePageTo: (uint) newPageNumber
    pageNumber = newPageNumber;

    [[NSUserDefaults standardUserDefaults]
        setInteger:pageNumber forKey:DEFAULTS_BOOKPAGE];
    [[NSUserDefaults standardUserDefaults] synchronize];

        [NSNumber numberWithInt:pageNumber]);

// Request controller from delegate
- (UIViewController *) controllerAtPage: (int) aPageNumber
    if (bookDelegate && [bookDelegate respondsToSelector:
        UIViewController *controller =
            [bookDelegate viewControllerForPage:aPageNumber];
        controller.view.tag = aPageNumber;
        return controller;
    return nil;

// Update interface to the given page
- (void) fetchControllersForPage: (uint) requestedPage
    orientation: (UIInterfaceOrientation) orientation
    BOOL sideBySide = [self useSideBySide:orientation];
    int numberOfPagesNeeded = sideBySide ? 2 : 1;
    int currentCount = self.viewControllers.count;

    uint leftPage = requestedPage;
    if (sideBySide && (leftPage % 2)) leftPage--;

    // Only check against current page when count is appropriate
    if (currentCount && (currentCount == numberOfPagesNeeded))
        if (pageNumber == requestedPage) return;
        if (pageNumber == leftPage) return;

    // Decide the prevailing direction, check new page against the old
    UIPageViewControllerNavigationDirection direction =
        (requestedPage > pageNumber) ?
        UIPageViewControllerNavigationDirectionForward :
    [self updatePageTo:requestedPage];

    // Update the controllers, never adding a nil result
    NSMutableArray *pageControllers = [NSMutableArray array];
    SAFE_ADD(pageControllers, [self controllerAtPage:leftPage]);
    if (sideBySide)
        SAFE_ADD(pageControllers, [self controllerAtPage:leftPage + 1]);
    [self setViewControllers:pageControllers
        direction: direction animated:YES completion:nil];

// Entry point for external move request
- (void) moveToPage: (uint) requestedPage
    [self fetchControllersForPage:requestedPage
        orientation: (UIInterfaceOrientation)[UIDevice

#pragma mark Data Source
- (UIViewController *)pageViewController:
        (UIPageViewController *)pageViewController
        (UIViewController *)viewController
    [self updatePageTo:pageNumber + 1];
    return [self controllerAtPage:(viewController.view.tag + 1)];

- (UIViewController *)pageViewController:
        (UIPageViewController *)pageViewController
        (UIViewController *)viewController
    [self updatePageTo:pageNumber - 1];
    return [self controllerAtPage:(viewController.view.tag - 1)];

#pragma mark Delegate Method
- (UIPageViewControllerSpineLocation)pageViewController:
        (UIPageViewController *) pageViewController
        (UIInterfaceOrientation) orientation
    // Always start with left or single page
    NSUInteger indexOfCurrentViewController = 0;
    if (self.viewControllers.count)
        indexOfCurrentViewController =
            ((UIViewController *)[self.viewControllers
    [self fetchControllersForPage:indexOfCurrentViewController

    // Decide whether to present side-by-side
    BOOL sideBySide = [self useSideBySide:orientation];
    self.doubleSided = sideBySide;

    UIPageViewControllerSpineLocation spineLocation = sideBySide ?
            UIPageViewControllerSpineLocationMid :
    return spineLocation;

// Return a new book
+ (id) bookWithDelegate: (id) theDelegate
    BookController *bc = [[BookController alloc]

    bc.dataSource = bc;
    bc.delegate = bc;
    bc.bookDelegate = theDelegate;

    return bc;
  • + Share This
  • 🔖 Save To Your Account