Can you use Swift to replace a UIPageView with a UICollectionView?

Image for post
Image for post

Can we create our own implementation of a UIPageController rather than just simply implementing a UICollectionViewController? You bet we can!

Prerequisites:

  • It would be beneficial to already have experience of using a UIPageController

Terminology

  • UIPageViewController: A container view controller often used for tutorial landing pages or feature lists. Most Apps use it.
  • UICollectionView: An object that manages an ordered collection of data items presented in a customizable layouts.

The problem (opportunity)

Instead of just using a UIPageController we can implement a UICollectionView. We need to make sure that the width of each cell is less than the screen width.

The difficulties — Paging

We will also need to make sure that we have paging disabled as we are not letting our UICollectionView clip to the normal upper-left hand corner of the view, but it’s center. To enable this we override scrollViewWillEndDragging;

of course we need to create our own mod function to allow for negative divisors:

The difficulties — UIPageControl

You need to programatically create your own UIPageControl

The difficulties — Rotation

When you rotate the device, you need to make sure that your cells are resized too:

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

The collection view could potentially scroll forever. This just means expanding the number of cells that need to be displayed when we get towards the end of our list. Perhaps the best strategy for this would be to actually store references to the cells, rather than the implementation here of just storing the number.

The Github link:

Link

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