Tutorial details

Page Control: Display view controllers as data pages | App Code for Sale | Preview

Page Control: Display view controllers as data pages | iOS Tutorial

We’ll create five instances of the same UIViewController to display all data we need

Overview PAGE TOP

The Page Control, is a useful tool that allows to display data on an iPhone app in the form of pages. To get the idea, just thing of the main screen of the iPhone, where you navigate among pages to the left and right to display all the apps existing on the device.

To be more accurate, the main idea when you use the Page Control in an app is that you create and use as many instances of UIViewControllers that will display data as the pages you want your app to have. Usually, you need to display various data on the same UIViewController, so it’s common to create instances only of one UIViewController. This is what we’ll do here, we’ll create five instances of the same UIViewController to display all data we need.

Another thing that should be cleared is the following: The view controller that uses the Page Control and the view controller that displays the data is not the same. That means that you need a view controller to set up the Page Control and implement all the navigational work and another (or more) view controller that will be used in combination with the first one to display your data. Be sure to make that clear to yourself if you want to get out of troubles and make your life easier.

Let’s get a little deeper before starting implementation. The whole idea is to use just two controls in the view controller where the Page Control will reside: A UIScrollView that will be used to display our pages and it will be responsible for navigating among them and of course the Page Control itself. As long as it concerns the data display, we already said that you need a new (or more) view controller.

A final note before proceeding. I found various examples and tutorials about that topic in many documentations and here I present a simple approach of my own. What I’ ll show here is not the only way that can be used to implement the page functionality in an app, there are more ways for sure, but this is my way and in my opinion it’s a fast implementation that totally serves our needs.

The sample app here is quite simple but it fully demonstrates the use of pages. The app will use the Page Control to display five (5) pages (all instances of the same view controller). Each page will have a different background color and a message that will show the number of the current page. Our target is to manage to navigate through the pages either by sliding left or right, or by tapping on the Page Control to move to the next or to the previous page.

Let’s get started. In Xcode (I use version 4.2) create a new Single View Application and name it PageControlTestApp (or whatever you wish). After your project is ready, add the view controller that will display the data in our pages.


Go to File–>New–>New File… and select the UIViewController subclass. Click Next and name the new view controller TestViewController (you may name it whatever you like, I’ll use that name). When the new view controller gets ready, open the TestViewController.xib file in the Interface Builder. In here, add a label (make it wide enough). In this label we’re going to show the index of each page.


We need to create a couple of outlets in the TestViewController.h file. Add the following lines:

1   @interface TestViewController : UIViewController
2   @property (retain, nonatomic) IBOutlet UIView *testView;
3   @property (retain, nonatomic) IBOutlet UILabel *lblMsg;

The testView outlet is the view of the TestViewController.

The lblMsg is the label we created in the previous step.

Go to the IB and connect these outlets to the view and the label equivalently. Don’t miss this step, you won’t see anything happening.

Don’t forget also to synthesize them in the .m file:

1   @synthesize testView;
2   @synthesize lblMsg;

Not finished yet. Release:

1   - (void)dealloc {
2       [testView release];
3       [lblMsg release];
4       [super dealloc];
5   }


The TestViewController will do the following: It will be provided with the index of the current page and depending on that value it will set a specific background color and display a custom message with page’s index. Therefore, a int value for the current page is necessary:

1   @property (nonatomic) int currentPage;

Synthesize it in the TestViewController.m file:

1   @synthesize currentPage;

We also need a method that will be called to setup the view. So add the next method in the TestViewController.h file:

1   -(void)updateView;

In the TestViewController.m file implement it. The comments are quite explanatory:

1   -(void)updateView{
2       // Depending on the currentPage value the message that will display the page number
3       // and the background color of the view will be set in here.
5       // Declare a UIColor object that will keep the backgroundcolor of the view depending on the currentPage value.
6       UIColor *bgClr;
8       // Check the currentPage value.
9       switch (currentPage) {
10          case 0:
11              bgClr = [UIColor whiteColor];
12              break;
13          case 1:
14              bgClr = [UIColor redColor];
15              break;
16          case 2:
17              bgClr = [UIColor yellowColor];
18              break;
19          case 3:
20              bgClr = [UIColor greenColor];
21              break;
22          case 4:
23              bgClr = [UIColor orangeColor];
24              break;
25          default:
26              break;
27      }
29      // Set the background color of the view.
30      [self.view setBackgroundColor:bgClr];
32      // Set the message of the label.
33      NSString *msg = [NSString stringWithFormat:@"This is page #%d", (currentPage + 1)];
35      // Update the label's message.
36      [lblMsg setText:msg];
37  }

That’s all about the TestViewController, the view controller that will display our data. Let’s go now to the real job.

As I said at the beginning of the post, we’ll create five instances of the TestViewController to present data in our pages. Before going any further though, let’s setup our view in the Interface Builder.


Open the ViewController.xib in the IB and add the following controls:

UIScrollView (X:0, Y:0, Width: 320, Height: 416)

Page Control (under the UIScrollView). Make sure to make the Page Control wide

enough if you want to make easy taps (or clicks in the Simulator). I have this frame: X: 0, Y: 424. Width: 320, Height: 36


Create the outlets for the controls we added in the previous step inside the ViewController.h file:

1   @interface ViewController : UIViewController ;
2   @property (retain, nonatomic) IBOutlet UIScrollView *scroll;
3   @property (retain, nonatomic) IBOutlet UIPageControl *pager;

Remember to connect them to the controls in the Interface Builder.

We also need:

  1. An array that will keep the view controllers that will be displayed in the pages.
  2. A value that will keep the number of the total pages.

In the previous code add the next two lines:

1   @property (retain, nonatomic) NSMutableArray *viewControllers;
2   @property (nonatomic) int totalPages;

Now synthesize all of them in the ViewController.m file:

1   @synthesize scroll;
2   @synthesize pager;
3   @synthesize viewControllers;
4   @synthesize totalPages;

Of course, now it’s the best time to release them:

1   - (void)dealloc {
2       [scroll release];
3       [pager release];
4       [viewControllers release];
5       [super dealloc];
6   }


Two things need to be done:

  1. Create a method that will initialize our objects.
  2. Create a method that will init and load an instance of the TestViewController for each of our pages (Step 4).

Here is the method that initializes the objects named (what else) initialize:

1   -(void)initialize{
2       // For the sake of the example, let's say that we want to have five pages.
3       totalPages = 5;
5       // Init the array of the view controllers that are going to be our pages.
6       viewControllers = [[NSMutableArray alloc] initWithCapacity:totalPages];
8       // So far so good.
9       // Let's init the scroll view and set the necessary properties.
10      // You may play around with these properties.
11      [scroll setPagingEnabled:YES];
12      [scroll setShowsHorizontalScrollIndicator:NO];
13      [scroll setShowsVerticalScrollIndicator:NO];
14      [scroll setScrollsToTop:NO];
15      [scroll setDelegate:self];
17      // Watch out the content size of the scroll view. It's important to understand that
18      // we want the scroll view to have the width of the screen (320.0 px in this example, only portrait orientation)
19      // multiplied by the total number of pages that will exist.
20      // This is how all of the view controllers are going to fit in the screen and make scrolling possible.
21      // The height is going to remain the same as we set it in the Interface Builder.
22      [scroll setContentSize:CGSizeMake(scroll.frame.size.width * totalPages, scroll.frame.size.height)];
24      // It's time to init the page controller.
25      // Tell the page controller how many pages are going to be.
26      [pager setNumberOfPages:totalPages];
27      // Also tell it what is the default and current page.
28      [pager setCurrentPage:0];
30      // Enough initializing.
31      // Let's load the pages for the first time.
32      for (int i=0; i        [self loadPageWithIndex:i];
33      }
34  }

As you can see, inside the for loop the loadPageWithIndex: method is called. It will be implemented in the next step.

For now, go to the viewDidLoad method and call our method. In this way, our objects will be initialized every time the view loads.

1   - (void)viewDidLoad
2   {
3       [super viewDidLoad];
4    // Do any additional setup after loading the view, typically from a nib.
6       [self initialize];
7   }


Now we’ll implement the loadPageWithIndex: method. This method will create an instance of the TestViewController every time that is called, it will provide the page index to that instance (remember the currentPage member variable in the TestViewController?) and it will force it to make all the necessary updates/changes using the updateView method of the TestViewController. After that, the view controller will be stored into the viewControllers array.

Here is the code:

1   -(void)loadPageWithIndex:(int)page{
2       // Check the index of the page and make sure that is greater than zero and lower than the totalPages value.
3       // This check is necessary to avoid errors even by mistake.
4       if (page < 0 || page >= totalPages) {
5           // In this case just return.
6           return;
7       }
8       else{
9           // The page index has a valid value.
10          // The TestViewController is going to be the view controller for the pages of this example.
11          // Init an instance.
12          TestViewController *testView = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:nil];
14          // The TestViewController view will display only a message with the number of the current page
15          // and a different background in each page. So, set the page number to the testView object.
16          // Of course, in a real app, this is the place where you'll provide any necessary data to the
17          // view controller that will be displayed and not the number of the current page.
18          // This is only for the example purposes.
19          [testView setCurrentPage:page];
20          // Update the view depending on the currentPage value.
21          [testView updateView];
23          // One more thing. The frame of the view controller must be set.
24          CGRect viewFrame = CGRectMake(scroll.frame.size.width * page, 0.0, scroll.frame.size.width, scroll.frame.size.height);
25          [testView.view setFrame:viewFrame];
27          // Add the view controller's view to the scroll view.
28          [scroll addSubview:testView.view];
30          // Add the testView view controller into the viewControllers array.
31          [viewControllers addObject:testView];
33          // The testView is no longer needed.
34          [testView release];
35      }
36  }


So far, every time our app loads our objects are initialized and the view controllers that display data in our pages are loaded as well. If you run the project right now in the Simulator you’ll see the first page with the specified background color and the appropriate message in the label, you may navigate to the next pages, but the Page Controller will not get updated.

What we need to do is to implement scrollViewDidScroll: delegate method (and that’s why we declared the UIScrollViewDelegate at Step 2). In every scroll/sliding/page transition we’ll figure out the current page index and we’ll update the Page Controller.

Here is the implementation:

1   // In every scroll (page transition) the page control needs to be updated
2   // to indicate the correct page displayed.
3   -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
4       // Calculating the page index. Not hard to understand it.
5       int page = floor(scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width);
7       // Set the page index as the current page to the page control.
8       [pager setCurrentPage:page];
9   }

If you try now to move from page to page in the Simulator you’ll notice that the Page Control is indicating the current page.

Nice, but is our Page Control working when we tap/click on it?


We need to create an IBAction that will be triggered every time the user taps on the Page Control. So, go to the ViewController.h file and declare this:

1   - (IBAction)changePage;

Go to the Interface Builder and connect the action to the Page Control.

Now go to the ViewController.m file and implement it:

1   // This action occurs when the user taps on the page control to change page.
2   - (IBAction)changePage {
3       // Get the index of the page.
4       int pageIndex = [pager currentPage];
6       // We need to move the scroll to the correct page.
7       // Get the scroll's frame.
8       CGRect newFrame = [scroll frame];
10      // Calculate the x-coordinate of the frame where the scroll should go to.
11      newFrame.origin.x = newFrame.size.width * pageIndex;
13      // Scroll the frame we specified above.
14      [scroll scrollRectToVisible:newFrame animated:YES];
15  }

That’s all. Now you have a fully working demo app that displays data pages using the Page Control.

I hope it becomes useful.

Here are the screenshots of the final result:


This tutorial was transferred as it was originally written in my blog, 

 therefore some techniques, tools or SDKs may have changed since then.

Reference PAGE TOP


0 Comments Leave a comment

Please login in order to leave a comment.

Newest first

to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.