Paging a overflowing collection view

In the last post, I discussed how to make a paging scroll view with hints on either side. This is a pretty common effect to try to achieve, and it’s nice to know that it can be done without too much effort now.

Of course, the natural progression of having many pages of views in a scrollview is to manage them with a UICollectionView. This complicates matters for us a lot, however. The collection view knows where all its cells are (no matter what layout you give it), so it automatically removes cells that are outside its visible bounds, the same way a tableview does. This breaks our clipsToBounds trick, because as soon as they move outside the bounds, they disappear.

But we are smarter than UICollectionView, and we will prevail.

Technique

Below is the simplest way to get the job done. It involves a collection view and an extra secret scroll view.

Set up your collection view

Set up your collection view and all its data source methods.

Frame the collection view; it should span the full width that you want to be visible.

As the scrollview moves, get its offset and set it to the offset of the collection view.

And you’re done! It’s a little less elegant than the previous solution, but this is the price we pay to get to use UICollectionView.

For extra credit: create a new UICollectionLayout subclass that overlaps the cells slightly and invisibly so that the collection view can’t remove those cells. (ed. I think this is impossible.)

I am Soroush Khanlou, and this is my blog. I write about programming, primarily Swift and Objective-C and learning what I can from other languages, like Ruby and Haskell. You can rarely catch me talking about things that aren't programming photography, travel, politics, eating, and fonts.