Monthly Archives: April 2015

Centered Paging with Preview Cells on UICollectionView

(Built on XCode 8.0 / Swift 3.0 – Code on BitBucket – perfected by Adam Kornfield)

We’ve all seen it: A collection view where a preview of the next cell is visible while the scrolling has a “paging” effect so that it always stops with a cell that is always centred.

Center

This is a simple exercise but interesting because of its use of an obscure function in the UICollectionViewFlowLayout class.

This gets called when the user lifts his finger and the collection view (which is a scroll view) starts decelerating and will return the content offset where the collection view should stop. Normally, its implemented by the superclass but here we need to override it. First however we must make some space for the first cell to scroll to the middle

The last declaration (proposed by tdavidson) will make for a more native feel that is closer to the UIScrollView.

As a tip, there is a way to add a custom UICollectionViewLayout to a UICollectionView from Interface Builder without losing the panel provided by the standard flow layout where you can set the size of the cell and the distance between them. This is done by not setting the layout to custom as below:

Screen Shot 2015-04-23 at 12.32.03

But by changing the class on the layout outlet itself:

Screen Shot 2015-04-23 at 12.36.04

The class is shown below:

The proposed offset is where the collection view would stop without our intervention. We peek into this area by finding its centre as proposedContentOffsetCenterX and examine our currently visible cells to see which one’s centre is closer to the centre of that area.

Center2

For more tutorials on Collection Views

[catlist name=”UICollectionView”]