An animated UIPageControl — from scratch in Swift

I wanted to create a UIPageControl with an animation of the main image, so that when it swipes in the image gets larger to appear nicely to the user.

Prerequisites:

  • Some experience of using UIPageViewController
  • A limited understanding of CGAffineTransform
  • An understanding of UIScrollview delegate methods
Image for post
Image for post

Terminology

  • CGAffineTransform: A feature of core graphics that allows animation in a nice and easy way.
  • UIPageController: A container view controller often used for tutorial landing pages or feature lists. Most Apps use it.

The problem (opportunity)

Lots of similar implementations use a scrollview and a Page Control to create their own version of the page view controller. However — a UIPageViewController already contains a scrollview! This is accessible and you are able to make your UIPageViewController a scrollview delegate

This allows you to access the scrollViewDidScroll delegate method.

However you need to be know which are the previous, current and next pages in your UIPageViewController — and this is possible through a scrollViewWillBeginDragging(_ scrollView: UIScrollView).

My implementation requires scrolling both left and right through the pages — necessitating use of a modulo function. As you may know, Swift’s % function computes the remainder of the integer division and this does not give the correct solution for negative numbers.

Within scrollViewDidScroll we calculate if we are moving from the left or the right through the offset of the scrollview.

If the percentageHorizontalOffset is < 0.5 we are swiping right, if it is more than 0.5 we are swiping left (0.5 is when the centre controller is right in the middle).

Other issues are positioning the UIPageControl correctly. The UIPageControl only displays when the presentationCount and presentationIndex are implemented, and the view is positioned in viewDidLayoutSubviews()

Which relies on the currentIndex being calculated as a computed property:

We need to be aware that programatically moving the page will also need to call the setVarsForScroll() method as scrollViewWillBeginDragging will obviously not be called by default.

Testing

As with much iOS coding testing is not so easy. Why not take a look at the Git link, and give me some feedback about my approach?

Conclusions

If we know that there is already a UIScrollview in a UIPageControl it would be rather remiss not to use it. In this circumstance instead of using our own version of UIPageControl we can use the inbuilt.

Link

Want to get in contact? Use 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