`

(转)How to Use UIPageViewController to Build Tutorial Screens

    博客分类:
  • IOS
阅读更多

转自:http://www.appcoda.com/uipageviewcontroller-tutorial-intro/

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.appcodain 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:

 

#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:

 

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:

 

#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:

 

- (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:

 

- (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:

 

- (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:

 

 

- (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.

 

分享到:
评论

相关推荐

    14 Build a WhatsApp Clone and learn to use Cloud Data Storage [Tutorial] 2/2

    14 Build a WhatsApp Clone and learn to use Cloud Data Storage [Tutorial] 2/2

    1 how to collect bank details edited_tutorial_

    "1 how to collect bank details edited_tutorial_" 这个标题暗示了这是一个经过编辑的教程,专门针对银行信息收集流程的优化。 首先,我们要理解银行详情通常包括哪些信息。一般来说,这包括银行名称、账户持有人...

    FLUENT 2020R2 tutorial guide PDF及案例源文件

    The ANSYS Fluent Tutorial Guide contains a number of tutorials that teach you how to use ANSYS Flu- ent to solve different types of problems. In each tutorial, features related to problem setup and ...

    OpenCV 3.x with Python By Example, 2nd Edition-Packt Publishing(2018).pdf

    Chapter 2, Detecting Edges and Applying Image Filters, shows how to use fundamental image- processing operators and how we can use them to build bigger projects. We will discuss why we need edge ...

    14 Build a WhatsApp Clone and learn to use Cloud Data Storage 1/2

    14 Build a WhatsApp Clone and learn to use Cloud Data Storage [Tutorial] 1/2

    Boost.Build_v2_User_Manual.pdf

    How to use this document If you've just found out about Boost.Build V2 and want to know if it will work for you, start with Tutorial. You can continue with the User documentation. When you're ready to...

    Beginning C# 2008 Databases From Novice to Professional

    A comprehensive tutorial on both SQL Server 2005 and ADO.NET 3.0, Beginning C# 2008 Databases explains and demonstrates how to create database objects and program against them in both T–SQL and C#....

    log4j-tutorial.zip_How To Change It

    This tutorial explains how to set up log4j with email, files and stdout. It compares XML to properties configuration files, shows how to change LogLevels for a running application. Furthermore, we ...

    Rational Rose Real Time Tutorial

    Rational Rose RealTime provides tutorials to help you learn how to use the main features of the development tool. There are two types of tutorials: hands-on and concept overviews. The hands-on ...

    opencv-tutorial-a-guide-to-learn-opencv

    1. **颜色空间转换**:OpenCV支持多种颜色空间的转换,如BGR to Gray,RGB to HSV等。 2. **图像滤波**:包括均值滤波、高斯滤波、中值滤波等,用于平滑图像或去除噪声。 3. **边缘检测**:Canny、Sobel、Laplacian...

    Docker Docker Tutorial for Beginners Build Ship and Run azw3

    Docker Docker Tutorial for Beginners Build Ship and Run 英文azw3 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书

    sbt in Action(Manning,2015)

    Next, it shows you how to use the peripheral libraries in sbt to make common tasks simpler. Finally, it covers how to deploy software effectively. You’ll learn to appreciate how sbt improves the ...

    Entity.Framework.Tutorial.2nd.Edition.1783550015

    The book aims to explain the concepts of the Entity Framework and illustrate how you can use these in applications with a tutorial based approach. Table of Contents Chapter 1: Introducing the ADO...

    Accelerated C# 2010

    Many books introduce C#, but very few also explain how to use it optimally with the .NET Common Language Runtime (CLR). This book teaches both core C# language concepts and how to wisely employ C# ...

    C# 2010捷径教程

    Many books introduce C#, but very few also explain how to use it optimally with the .NET Common Language Runtime (CLR). This book teaches both core C# language concepts and how to wisely employ C# ...

    Android代码-java8-tutorial

    Backed by short and simple code samples you'll learn how to use default interface methods, lambda expressions, method references and repeatable annotations. At the end of the article you'll be ...

Global site tag (gtag.js) - Google Analytics