How to Use UIPageViewController to Build Tutorial Screens

110 Flares 110 Flares ×

Editor’s note: For the very first time you launch an app, you’ll probably find a series of tutorial screens to walk you through the basic features. It’s a common practice to explain how the app works. This week, we’ll show you how to build a similar type of tutorials by using UIPageViewController.

The UIPageViewController class was introduced into the iOS 5 SDK as a mechanism to implement a page turning style of user interface in iOS applications. The UIPageViewController is a highly configurable class that it lets developers to configure:

  • the orientation of the page views – vertical or horizontal
  • the transition style – page turning style or a dot based style
  • the axis (spine) on which the page will turn

In this tutorial we are going to show how to use the UIPageViewController to implement an app that allows users to scroll between multiple screens. You can find examples of this type of page view implementation in games like Angry Birds to show the available levels or in apps that include tutorial/walkthrough screens.

Sample Walkthrough Screens from Path

Sample Walkthrough Screens from Path

Prior to iOS 5 we had to use the UIPageControl class and explicitly control the animations, as well as, transitions between pages. This procedure has been highly simplified with the introduction of the UIPageViewController. We’ll keep the demo app very simple and focus to demonstrate the usage of UIPageViewController. However, with the basic understanding of the page view controller, you can easily build the tutorial screens in your app.

A Glance at the Demo App

The application we are going to create is very simple: it consists of five different screens that each page displays a unique screen label. You’re allowed to navigate between pages by swiping through the screen.

pageviewcontroller1

Creating the Project

Open Xcode and create a new Project by using the Single View Application template. It might seem a little bit strange to select the Single View Application template as Xcode already comes with a Page-Based Application template, which contains a fully functional app based on the UIPageViewController. However, this template is a little bit complex and it will take us more time to clean-up the code of the template than to start from scratch. Needless to say, we can better grasp the concept behind the UIPageViewController when we start from scratch.

UIPageViewController Demo Project

Creating a new project using Single View Application template

Okay, let’s move on. In the next screen enter PageApp as the product name and set com.appcoda in the company identifier field. Select the Use Authomatic Reference Counting option, but unselect the Use Storyboard since we’re not going to use storyboards for this project. Press next and create the project. Then, select the APPViewController.xib file and change the background of the view to black color.

Creating the Tutorial Screen

The next step is to implement the view controller class that we use to display our five tutorial screens. Select File -> New -> File … and from the list of available templates, select the “Objective-C class” template. Name the class APPChildViewController and make it a subclass of UIViewController. Also, check the box labeled “With XIB for user interface” in order to create the corresponding user interface.

Select the APPChildViewController.xib file just created. Change the background of the view to Black and reduce the vertical size of the view to 512 points to leave some free space for the dots of the page controller (which has a default height of 36 points). Finally add a white UILabel centered on the screen, with a big font size, and change its content to “Screen #n”. The resulting view should look something like:

User Interface for the main screen

User Interface for the main screen

Note: We keep the five tutorial screens very simple that it only displays the screen number in each screen. In the actual app, you may display images to elaborate your app feature.

Next, we have to create an IBOutlet for that label. In order to do that, change the Editor to the Assistant mode meanwhile the APPChildViewController.xib file is selected. The APPChildViewController.h file should be opened. Control and drag from the UILabel to the APPViewController.h and create an IBOutlet. Set the name as screenNumber. Finally, create a new property of type NSInteger called index. The resulting APPChildViewControl.h file should be something like:

1
2
3
4
5
6
7
8
#import <UIKit/UIKit.h>

@interface APPChildViewController : UIViewController

@property (assign, nonatomic) NSInteger index;
@property (strong, nonatomic) IBOutlet UILabel *screenNumber;

@end

The index property allows us to control which screen is currently shown. In order to do that, once we have created a child screen, we have to set up its index through the index property. At the same time, we update the text of the label as well. Add the following line of code to the end of the viewDidAppear: method in the file APPChildViewController.m:

1
self.screenNumber.text = [NSString stringWithFormat:@"Screen #%d", self.index];

Handling the View Controllers

The UIPageViewController class highlights the distinction between a view controller and a container controller. The container controller is used to contain and manage multiple view controllers shown in the app, as well as, controlling the way one view controller switches to another. Here the UIPageViewController is the container controller that lets the user navigate between pages of content, where each page is managed by its own view controller object.

In order to make UIPageViewController work, our APPViewController has to adopt the UIPageViewControllerDataSource protocol. By implementing the data source protocol, we tell the page view controller what to display for each page.

Open the APPViewController.h file and modify the @interface declaration, and add a new property to hold the UIPageViewController:

1
2
3
4
5
6
7
#import <UIKit/UIKit.h>

@interface APPViewController : UIViewController <UIPageViewControllerDataSource>

@property (strong, nonatomic) UIPageViewController *pageController;

@end

Next, we have to implement at least two methods of the protocol:

  • viewControllerAfterViewController – provides the view controller after the current view controller. In other words, we tell the app what to display for the next screen.
  • viewControllerBeforeViewController – provides the view controller before the current view controller. In other words, we tell the app what to display when user switches back to the previous screen.

Add the following lines of code before the end of the APPViewController.c file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
   
    NSUInteger index = [(APPChildViewController *)viewController index];
   
    if (index == 0) {
        return nil;
    }
   
    index--;
   
    return [self viewControllerAtIndex:index];
   
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
   
    NSUInteger index = [(APPChildViewController *)viewController index];
   

    index++;
   
    if (index == 5) {
        return nil;
    }
   
    return [self viewControllerAtIndex:index];
   
}

The above methods are very straightforward. We simply increase/decrease the screen number and return the view controller to display. However, please note that we have to check if we have reached the boundaries of the pages and return nil in that case. In the demo app, we have a maximum of five pages. So we’ll return nil if user has come to the end of the pages.

As you may wonder, there are two ways to create the view controllers for the container. We can either create them all at once and put them into the container. However, this way is not recommended as it takes up too much resources. Another way is to create the view controller only when they are needed. Here, the “viewControllerAtIndex” method is designed for this purpose. It takes in the index parameter and creates the corresponding view controller (i.e. APPChildViewController) on the fly.

Add the following method at the end of the APPViewController.m file:

1
2
3
4
5
6
7
8
- (APPChildViewController *)viewControllerAtIndex:(NSUInteger)index {
       
    APPChildViewController *childViewController = [[APPChildViewController alloc] initWithNibName:@"APPChildViewController" bundle:nil];
    childViewController.index = index;
   
    return childViewController;
   
}

Finally, you have to tell iOS the number of dots to display in the page view controller and which dot must be selected at the beginning. Add the following two methods at the end of the APPViewController.m file:

1
2
3
4
5
6
7
8
9
- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController {
    // The number of items reflected in the page indicator.
    return 5;
}

- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController {
    // The selected item reflected in the page indicator.
    return 0;
}

Again the above code is very straightforward. We simply tell iOS that we have 5 pages to display in the page view controller and the first page should be selected by default.

Initializing the UIPageViewController

The final step is to create and initialize the UIPageViewController. The best place to do that is in the viewDidLoad method. Open the APPViewController.m file and change the method to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void)viewDidLoad {
   
    [super viewDidLoad];
   
    self.pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
   
    self.pageController.dataSource = self;
    [[self.pageController view] setFrame:[[self view] bounds]];
   
    APPChildViewController *initialViewController = [self viewControllerAtIndex:0];
   
    NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
   
    [self.pageController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
   
    [self addChildViewController:self.pageController];
    [[self view] addSubview:[self.pageController view]];
    [self.pageController didMoveToParentViewController:self];
   
}

Let’s see what the method does. We first create the UIPageViewController object and specify the navigation style, as well as, the navigation orientation. Here we use UIPageViewControllerTransitionStyleScroll as the transition and UIPageViewControllerNavigationOrientationHorizontal as orientation. Please note that the transition using dots is only available if we use an horizontal orientation and a scroll style. Other orientations or transitions styles will default the switch to a page turning style.

Next we specify the data source, in this case it is the class itself. We also modify the frame of the controller in order to opt for the full screen. We then create the first child screen and add that screen to an array of controllers. We do not add more controllers to the array of controllers as we have opted to create them on demand.

And finally, we have to replace the current controller by our new page controller, and to add the page controller view to the current view.

Compile and Run the App

And there we go, start the application and see how the UIPageViewController works. You should be able to test the page view controller by using the iPhone Simulator. Try to swipe through the screen to navigate between pages.

PageView Demo App

PageView Demo App

Download Full Source Code

In this tutorial, we have given a basic introduction of UIPageViewController. This is a very handy class for implementing tutorials in your app. Try to modify the sample app and build a more elegant tutorials.

For your complete reference, you can download the full source code from here. As always, leave us comment and share your thought.

Stay tuned. We’ll have a few more tutorials in the coming weeks.

You May Like These:

Get Free Chapters of Our AppCoda Book

Learn iOS 7 Programming from Scratch

The Learn iOS 7 Programming from Scratch is a 400-page eBook written for beginners with little or even no programming experience. It is based on the tutorials of our popular programming course. The book starts with the basics and walks you through the process to create iOS apps using iOS 7 SDK and Xcode 5. Want to learn more? Check it out here and get two free chapters.


Build Your Own Game and Monetize on the Side

Learn how to develop your first iOS game and make money on the side. The starter kit will come with full source code of a memory game for both iPhone and iPad, as well as, a complete guide to explain how the code works. Check out the starter kit to learn more.


  • Ирина Антонюк

    Thanks a lot for this lesson… It`s very in time for me! Looking forward for new one…

  • David

    Great! Awesome! as normaly

  • LittlePeculiar

    Very Cool app. As always, thank you for this site. It’s become my favorite for iOS tutorials.

    Awesome

    • http://www.simonblog.com Simon Ng

      Thanks! Glad to hear that :-)

  • lanqy

    On iPhone 4S the dots Page controller doesn’t show,I try to change the view height but doesn’t work, how to show the dots page?

    • KingG

      hi, i think it shows….maybe u have to scroll down…:)

  • Hunt

    Many thanks! I have a question. How to scrolling automaticaly beetwen screens?

  • John R Dempsey

    I cant tell where the .c file is as I dont seem to have one while following this tutorial … any help would be appreciated :)

    • Erik Fisher

      It’s just a typo. It’s supposed to say APPViewController.m;)

  • Ranjit

    Hi, thanks for your blog, but I think their is a bug in this project, the index is not getting updated properly.

    • newbie1

      i am getting error “no visible @interface for declares the selector ‘viewControllerAtIndex’ ”
      Any idea why this would be ?

  • Dave Haupert

    I appreciate this tutorial so much- but it appears to have a memory leak. I put a dealloc routine in the AppChildViewController and set a breakpoint and it is never called. the viewControllerAtIndex gets called for viewcontrollers already created. I’m going to change things up to cache them somehow but wanted to give you the heads up!

  • Pingback: PageViewController delegate functions called twice | BlogoSfera

  • Pingback: PageViewController delegate functions called twice | BlogoSfera

  • Nic

    Nice tutorial. Big thanks!! But why would we have to change the vertical size ??
    I see no difference between before-and-after changing. Dots still show up and distance remains the same.
    Thanks for your explanation.

  • 座頭市

    @property (assign, nonatomic) NSInteger index;

    How to connect? just a write?

    • azam

      you don’t connect NSInteger. it is not UI element.

  • 座頭市

    This course ask for the detailed description.

  • pdxbenjamin

    I’m having an odd issue with the instruction “reduce the vertical size of the view to 512 points” my height option is grayed out and un-changeable

    • mikkkkk

      Check the Attributes inspector, under Simulated Metrics. The size should be “Freeform”.

  • Mohammed Gritli

    can you please do another tutorial using storyboards !!! i’d really appreciate it

  • Jorge Costa

    Hi Simon, great tutorial! Simple as normaly.

    I have a question for you… I’m trying to add buttons to jump to a specific page, do you know how to do that?

    Cheers,

  • Pingback: using uipageviewcontroller to show full size images | BlogoSfera

  • Pingback: using uipageviewcontroller to show full size images | BlogoSfera

  • bruce

    Good tutorial. But I have a question. How to add a home page button on the screen interface, so that I can click the home page,it will go to the first page.
    Another question is that if the each page has voice file, how to turn the page automatically after the audio of a page finish playing. Thanks.

    • neel

      Hello bruce,

      did you get answer for your question, since i am also looking for a solution where how to add a home page button on the screen interface, so that i can click the home page, it will go to the first page. And after that one more question, how to attached voice file with each pages and if the page turn automatically or manually then accordingly audio of a page finish playing thanks.

  • Carlos Torres

    How can I unbounce it?

  • leancuisine

    Anyone wanting to try this with Storyboard should alter the function – (AppChildViewController *)viewControllerAtIndex:(NSUInteger)index in APPViewController.m

    Swap this:
    APPChildViewController *childViewController = [[APPChildViewController alloc] initWithNibName:@”APPChildViewController” bundle:nil];

    for this:
    UIStoryboard* sb = [UIStoryboard storyboardWithName:@"myStoryboard" bundle:nil];
    APPChildViewController *childViewController = [sb instantiateViewControllerWithIdentifier:@"myStoryboardID"];

    (“myStoryboard” is the name of your projects storyboard as visible in the project navigator (file list). “myStoryboardID” is the ID you set on the APPChildViewController using interface builder.)

    A big thank you to AppCoda for your great tutorials!

    • Eric Roland Goldberg

      You can just use “self.storyboard” instead of storyboardWithName:bundle: if you’re calling it from within a view controller that is itself instantiated from a Storyboard. More modular that way.

    • http://tywhite.blogspot.com tywhite

      How do I set the ID on APPChildViewController in interface builder? I’m in Xcode 5, so no option but to have a storyboard present, but I don’t know how to get APPChildViewController into the storyboard, let alone set an ID on it. Help! (And sorry for being a n00b)

      • Eftixia Happines

        please share how?

  • http://tywhite.blogspot.com tywhite

    Would love if this tutorial would get updated for XCode 5 — I’m a first timer and running into all sorts of issues that I suspect are merely from the slightly different setup.

  • Ivan

    Definitely best iOS tutorials that I’ve seen so far

  • Hugh Jeremy

    How can you make it go back to the first page after you’ve reached the last page, and go to the last page with a left swipe from the first page?

  • John R Dempsey

    I need to access the pageControl dots – I have used the tutorial above and it works great but I cant figure out how to move the pageControls location or how to access it to change the dots tint color. Any help on this will be greatly appreciated.

  • John R Dempsey

    I found the answer you need to do this in the controller that sets the pageController

    NSArray *subviews = self.pageController.view.subviews;

    UIPageControl *thisControl = nil;

    for (int i=0; i<[subviews count]; i++) {

    if ([[subviews objectAtIndex:i] isKindOfClass:[UIPageControl class]]) {

    thisControl = (UIPageControl *)[subviews objectAtIndex:i];

    }

    }

    This will allow you to access the pageControl element

  • Pingback: Does somebody know a good UIPageViewController tutorial? - QueryPost.com

  • htta

    fake

  • Mohamed

    it’s a very good tutorial; please can you tell me how pass the image from page controller view to another view controller after select it(by one touch); please help me

    • Nick G.

      First, create a segue between the View Controller with the images and the destination controller, then create in the View Controller with the images a prepareForSegue method.

  • H.S.H

    Hello,
    I have a question:
    how can I enable the user to indicate the number of pages rather than setting it myself?
    thanks in advance

  • Bruno Santos

    I added some images to each page and I want the dots to appear in front of the pages, but I having trouble in doing that. The black background appears with the dots appears in front of the images.

    Can anyone help me with that?

  • Gerard Grundy

    Hi awesome tutorial! I have added this to a previous app of mine and managed to load the tute view though how can I return to my app after the last page is viewed? My app is in storyboard.

  • Pingback: Tutorial screens for app | StackAnswer.com

  • iOSNewbie

    NSUInteger index = [(APPChildViewController *)viewController index]; in viewControllerBeforeViewController gives the error no visible @interface for APPChildViewController declares the selector index. Anyone knows why?

    Thanks

    • iOSNewbie

      My Bad. I had a typo. Works fine. thanks

  • Pingback: UIPageViewController | My daily learning

  • TheKog

    My question is about the array of viewControllers created in viewDidLoad. You added the initial childViewController to the array and initialized the pageController with setViewControllers. Later when anvigation causes you to allocate additional childViewControllers and you return them in the viewControllerBefore/After methods, are they added to the array by the system? I am confused as to whether the app needs to manage its own array of childViewControllers or not for correct memory usage and proper dynamic allocation of childViewControllers. And finally shouldn’t you free up childViewControllers at some point? What if you were page swiping through 100 pages each with various images? At some point pages should be freed up – how would you handle this? Thanks in advance your tutorial was useful but my questions are relative to Apple’s PageControl tutorial as related.

  • Behinder

    Did nobody do tutorial of uipageview controller using storyboards which is preffered way of doing things in xcode 5? :(

  • Play Lotto

    How to dismiss the tutorial and go back to your app?
    I am trying to put an exit button, but it’s not working…it would be great to implement the tutorial screen with a demo app or empty view to back to
    thanks a lot

  • Akashshr

    Thanks! Appreciate a good tut

  • Irina

    If you swipe super fast, at some point the dots stop showing the correct placement.

  • Pingback: Condition based swipe to next view controller – UIPageViewController

110 Flares Twitter 26 Facebook 64 Google+ 19 LinkedIn 1 110 Flares ×