Skip to main content

How to Use UIPageViewController in iOS - Objective C

UIPageViewController




Objective

This blog post gives introduction to the UIPageViewController in iOS.
Introduction:
UIPageViewController is used to navigate between the screens or in simple words pages with animations. The screen navigation is controlled by the user gestures. Smart phone users are aware of the scrolling between the pages in the Home Screen of the device. This is done by the use of UIPageViewController. UIPageViewController in iOS is a highly configurable class.
We are allowed to define:
Orientation of the page viewsvertical or horizontal
Transition stylepage curl transition style or scrolling transition style
Occasion of the spineonly applicable to page curl transition style
Space between pagesonly applicable to scrolling transition style to define the inter-page spacing
In this post I am going to create a simple example of UIPageViewController which uses the scroll transition style to navigate between three screens which will have 3 different images of cartoon characters. So, lets get started.

Step 1 Create Xcode Project for UIPageViewController

Create a new xcode project for UIPageViewController example under the iOS Application and create single view application. Here we can see that page based application is also available for navigating through pages, but in this post I am concentrating upon navigation between different pages or screens using UIPageViewController, which is easier than page based application.
Here, I am giving the iOS Page View Controller product name as PageViewDemo. And the and organisation name as com.iostutorialpoints You can enter the product name and organisation name as per your preference. Press next and store the Page View Controller Tutorial project according to your preference.
Press create, and the project for Xcode Page View Controller in iOS is created.

Step 2 Design UI

Drag a new PageViewController which is subclass of UIPageViewController. And a new ViewController on to the storyboard.
The UIPageViewController storyboard shall look as shown below: 
pageview controller

Step 3 Add ViewControllers

In this iOS PageViewController tutorial, the original view controller is used as the root view controller for holding the page view controller. The view controller we've just added will be used for displaying the page content. Throughout the post, we will refer the original view controller as the root view controller and the other view controller as page content controller. For that delete the default viewcontroller.h and viewcontroller.m files and create new class under the UIViewController Class and name it as RootViewController.
In the 3rd inspector of default view controller in the class section select RootViewController, hence the default view controller inherits from the RootViewController class. Similarly for the page content view controller create a new class under the UIViewController and name it as PageContentViewController. And in the 3rd inspector of new view controller select the class as PageContentViewController which means the new view controller inherits from PageContentViewController.
Now the two view controllers titles will appear as shown below:
root view controller

Step 4 Set storyBoard ID

Next we will assign Storyboard ID for PageViewController and PageContentViewController which we will use later in our code. For that select the PageViewController and in the identity inspector enter the text PageViewController, also select PageContentViewController and in the identity inspector enter text PageContentViewController
select-page-content-view-controller

select-the-pageview-controller

By default, the transition style of the page view controller is set as Page Curl. The page curl style is perfect for book apps. For navigating between screens, we will use scrolling style. So change the transition style to Scroll under Attribute Inspector. 
scroll-under-attribute

Step 5 Design UI

Now we will create the user interface for the PageContentViewController for that drag ImageView and Label on to the PageContentViewController’s view put the label on to the ImageView in the upper portion. The ImageView will contain different images for different screens and the label will have some text about the image. Change the label text color to pink color.
The PageContentViewController will look as shown below: 


page-content-view-controller

For the root view controller, add a "Start Again" button and put it at the below of the screen. 
start-again-button 

Step 6 Create IBOutlet

Now create an Outlet from the ImageView and Label in the PageContentViewController.h file and name it as ivScreenImage and lblScreenLabel respectively. 
imageview-and-label

Next we create NString for holding the current images file and current image text for that we add the following line of code in PageViewController.h file. Also we will have NSUInteger for keeping page index.
@property NSUInteger pageIndex;
@property NSString *imgFile;
@property NSString *txtTitle; 

And in the PageContentViewController.m file in the ViewDidiLoad Method implement the following line of code:
- (void)viewDidLoad
{
     [super viewDidLoad];
     self.ivScreenImage.image = [UIImage imageNamed:self.imgFile];
     self.lblScreenLabel.text = self.txtTitle;
}


Step 7 Intialized UIPageViewController

In order to make UIPageViewController work, we must adopt the UIPageViewControllerDataSourceProtocol. The data source for a page view controller is responsible for providing the content view controllers on demand. By implementing the data source protocol, we tell the page view controller what to display for each page.
In this case, we use the RootViewController class as the data source for the UIPageViewController instance. Therefore it is necessary to declare the RootViewController class as implementing the UIPageViewControllerDataSource protocol.
The RootViewController class is also responsible to provide the data of the page content (i.e. images and titles). Open the RootViewController.h.
Add the following line of code:
@interface RootViewController : UIViewController
<UIPageViewControllerDataSource>

@property (nonatomic,strong) UIPageViewController *PageViewController;
@property (nonatomic,strong) NSArray *arrPageTitles;
@property (nonatomic,strong) NSArray *arrPageImages;

- (PageContentViewController *)viewControllerAtIndex:(NSUInteger)index;
- (IBAction)btnStartAgain:(id)sender;
@end 

In the RootViewController.m file initialise the arrays for page images and page titles in ViewDidLoad Method:
[super viewDidLoad];
arrPageTitles = @[@"This is The App Guruz",@"This is Table Tennis 3D",@"This is Hide Secrets"];
arrPageImages =@[@"1.jpg",@"2.jpg",@"3.jpg"]; 



Step 8 Delegate & Datasource Method

Next we will add the two required methods for the UIPageViewDatasource in the RootViewController as follows:
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController 
{
     NSUInteger index = ((PageContentViewController*) viewController).pageIndex;
     if ((index == 0) || (index == NSNotFound))  {
        return nil;
     }
     index--;
     return [self viewControllerAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
     NSUInteger index = ((PageContentViewController*) viewController).pageIndex;
     if (index == NSNotFound)
     {
         return nil;
     }
   index++;
   if (index == [self.arrPageTitles count])
   {
       return nil;
   }
return [self viewControllerAtIndex:index];
}
Here you can see that we have created a helper method i.eviewControllerAtIndex:index.
The definition for this method goes as below:
- (PageContentViewController *)viewControllerAtIndex:(NSUInteger)index
{
     if (([self.arrPageTitles count] == 0) || (index >= [self.arrPageTitles count])) {
        return nil;
     }
     // Create a new view controller and pass suitable data.
     PageContentViewController *pageContentViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageContentViewController"];
     pageContentViewController.imgFile = self.arrPageImages[index];
     pageContentViewController.txtTitle = self.arrPageTitles[index];
     pageContentViewController.pageIndex = index;
     return pageContentViewController;
}
To display a page indicator, you have to tell iOS the number of pages (i.e. dots) to display in the page view controller and which page must be selected at the beginning. Add the following two methods at the end of the RootViewController.m file.
-(NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController
{
     return [self.arrPageTitles count];
}

- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController
{
     return 0;


Step 9 Add PageView Controller

In this final step we will create and initiate the UIPageViewController and for that we will make use of the Storyboard ID of the PageViewController. Remember we discussed that we will use the Storyboard ID further in our code. Hence change the ViewDidLoad method to:
- (void)viewDidLoad
{
     [super viewDidLoad];
     arrPageTitles = @[@"This is The App Guruz",@"This is Table Tennis 3D",@"This is Hide Secrets"];
     arrPageImages =@[@"1.jpg",@"2.jpg",@"3.jpg"];

     // Create page view controller
     self.PageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageViewController"];
     self.PageViewController.dataSource = self;
     PageContentViewController *startingViewController = [self viewControllerAtIndex:0];
     NSArray *viewControllers = @[startingViewController];
     [self.PageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];

     // Change the size of page view controller
     self.PageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 30);
     [self addChildViewController:PageViewController];
     [self.view addSubview:PageViewController.view];
     [self.PageViewController didMoveToParentViewController:self];
}


Step 10 Set PageViewController in AppDelegate

In this step we customise the look of the PageView i.e. we will change the color of the dots in the PageView. For that add the following lines of code in the AppDelegate.m file in didFinishLaunchingWithOptions method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     UIPageControl *pageControl = [UIPageControl appearance];
     pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
     pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
     pageControl.backgroundColor = [UIColor whiteColor];
     return YES;
}
  • 1
  •  
  • 2
  •  
  • 3
I hope you will find this blog post very useful. While working with UIPageViewController in IOS. Let me know in comment if you have any questions regarding UIPageViewController in IOS. 

Comments

Popular Posts

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...