Using UIPageController in iOS

Image for post
Image for post

A UIPageController manages the navigation between pages of content. Each page is managed by a child view controller.

It does seem that such a commonly used feature of iOS should be easy to use, but there are a few issues in the implementation that can cause one to get stuck — like if you don’t want the UIPageControl to have a black background at the bottom of the screen!

Prerequisites:

  • Some understanding of view controllers and gestures
  • Some understanding of UIScrollView

Terminology

UIPageController: A container view controller often used for tutorial landing pages or feature lists. Most Apps use it.

The theory

When using a Page controller you will be set up with a content view that will hold a _UIQueuingScrollView as well as the UIPageControl (if any). This setup ensures that the UIPageControl does not scroll with the view that the user scrolls.

Practical examples

A UIPageController can be set up a number of ways, depending on the amount of flexibility you require.

The simple example with (or without) a UIPageControl()

We can setup a UIPageViewController in a Single View App, and this can even be our initial view controller.

This will also need to conform to UIPageViewControllerDataSource and UIPageViewControllerDelegate:

viewControllerAfter step by step

We can look at the viewControllerAfter function in detail, and this is the one that is called when you scroll forwards (from right to left) in the UIPageViewController.

First the function makes sure that there is a current view controller index, and if not return:

we can then derive that we will want to move to the next index.

If the user is on the last view controller, give them the first view controller. If the next index is larger than the maximum number of view controllers something has gone hideously wrong, and we should not return anything.

And, almost there, we will (if we have got this far) return the next view controller in the array:

Allowing a UIPageControl

We will need to create a variable for the currentIndex, and have two functions

  • presentationCount
  • presentationIndex

and in our implementation this looks like the following:

However, most implementations do not want this look having the black bar at the bottom of the view controller

The issue is that the UIPageViewController restricts the size of the view controller so as to not extend beneath the UIPageControl. We can override viewDidLayoutSubviews() which will extend the UIScrollview to the size of the screen.

Equally we can manipulate the location of the PageControl in this function:

Here is the code for the full UIPageViewController:

Want to get in contact? Have a question? Hit me up on Twitter:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store