Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDK. Save $177 with coupon code LBOC.

Active Filters: Collection Views

In Bite #241, we learned about all the great improvements to UICollectionView's cell lifecycle in iOS 10. Today we'll check out another iOS 10 improvement to UICollectionView: The prefetchDataSource! Let's get started.

UICollectionView gains a new property this year called prefetchDataSource. Just like the existing delegate and dataSource properties, we an simply set it to some object that implements the new UICollectionViewDataSourcePrefetching protocol.

This protocol is brand new in iOS 10, and requires we implement just one new function:

public func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath])

When this function is called, we can examine the indexPaths array we're passed in to know which cells are "coming up soon" and thus which cells we should probably begin loading the data for. The indexPaths will be ordered "ascending by geometric distance" which basically means the indexPaths that need to be displayed on screen soonest will be first.

Let's use this new functionality to let our UICollectionView pre-load the images that go in our cells, This way when they scroll on screen, the images will already be visible and won't have to "load in" in front of the user. Classy! 🎩

class SpaceshipsViewController : UICollectionViewController {
  override func viewDidLoad() {

    collectionView?.prefetchDataSource = self

extension SpaceshipsViewController : UICollectionViewDataSourcePrefetching {
  func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
    ImagePreloader.preloadImagesForIndexPaths(indexPaths) // happens on a background queue

  func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) {
    ImagePreloader.cancelPreloadImagesForIndexPaths(indexPaths) // again, happens on a background queue

That's literally it. We make sure to implement the optional cancelPrefetchingForItems function so that we don't waste resources preloading images the user won't actually see.

UICollectionViewDataSourcePrefetching doesn't replace our existing data loading architecture/functionality. It's essentially a hint as to which cells will be displayed soon, and which ones we might want to begin loading content for.

Finally, just like in Bite #241, we can opt-out of this new prefetching behavior by either simply leaving prefetchDataSource set to nil, or by setting isPrefetchingEnabled to false.

Oh one more thing: All of this works exactly the same on UITableView too now, thanks to the (almost identical) new UITableViewDataSourcePrefetching protocol.

UICollectionView is one of the most important tools in our toolbox as iOS developers. Achieving smooth scrolling performance is a badge of honor for many of us. This year in iOS 10, Apple has made substantial changes to how cells make their way into collection views.

Today we'll take a look at these changes, and how we can take advantage of them in our apps. Let's dive in! 🏊

Here's the TLDR:

UICollectionView will now call cellForItemAtIndexPath: way before it used to. Sometimes the cells we return from that function won't even end up being displayed. We should proceed accordingly.

This dramatically improves scrolling performance as the system intelligently manages everything, giving us beautiful, buttery-smooth, 60fps scrolling. Neat!

Here's the slightly more wordy version:

In iOS 10, Apple has enhanced UICollectionView's ability to "pre-load" cells before they appear on screen.

Essentially, UICollectionView is now aware of the direction the user is scrolling, and will "look ahead" to cells that will be coming on to screen soon, call the appropriate existing delegate functions (like cellForItemAtIndexPath:) as needed.

Let's look at how the UICollectionViewCell lifecycle has changed in iOS 10. We'll start with how things are today, in iOS 9:

First, cellForItemAtIndexPath: is called, and we dequeue a cell. UICollectionView pulls it from the reuse queue, and calls prepareForReuse on it.

Next, we'll configure the cell to our needs. Setting the content of labels, etc.

Then, right before the cell is scrolled into view, willDisplayCell:atIndexPath: is called.

The user looks at the beautiful cell we've created until they grow tired of it, and eventually scroll it off screen.

At this point, we'll get a didEndDisplayingCell:atIndexPath: call, and our cell will re-enter the reuse queue.

If the user changes their mind and scrolls back up, the whole process starts over with cellForItemAtIndexPath: 😨

Now, how about in iOS 10? Next we'll look at how this process has improved:

In iOS 10, things are mostly the same, all the way up until the point where the cell goes off screen at the end.

Yes, didEndDisplayingCell:atIndexPath: is called as usual, but the cell is not immediately put into the reuse queue.

Instead, the system keeps it around for a bit. This way, if the user starts scrolling the other direction, the cell is already ready to be displayed on screen again. Very cool!

UICollectionView also has a new trick when working with multi-column layouts.

(This is where the “prefetching” bit comes in).

In these layouts, the system will optimize for scrolling performance by sending cells through their lifecycle sooner, at times determined intelligently by the system.

Cells will go through their lifecycle one at a time, each being created via an incoming call to cellForItemAtIndexPath:.

Later, once the entire "row" of cells is about to be scrolled on to screen, willDisplayCell:atIndexPath: will be called on each cell.

Apple describes cell pre-fetching as an "adaptive" technology. In other words, it will respond to how users are interacting with our apps.

For example, UICollectionView will try to look for "down time" when the user isn't scrolling (or at least isn't scrolling quickly) to prefetch some cells. If the user begins wildly scrolling very quickly, cell prefetching will stop until they slow down.

Finally, here's some general advice and info that we should consider when architecting our UICollectionView code going forward:

  • Set up our cells in cellForRowIndexPath:, try to keep the willDisplay/didEndDisplay callbacks light weight.

  • We should now expect some cells to be created (cellForItemAtIndexPath:) but never displayed.

If for some wacky reason we didn't want this wonderful new behavior, we can set our collection view's isPrefetchingEnabled property to false (it defaults to true in iOS 10).

These improvements are obviously really great, but what about actually doing the work of loading the data that gets displayed in our cells. Well, for that you'll have to come back for tomorrow's Bite!

In iOS 9, UICollectionView learned to interactively re-order cells. Let's take a look.

Before we dive in, one quick note: If we just need re-orderable cells, adopting this functionality can be incredibly simple:

override func collectionView(collectionView: UICollectionView, moveItemAtIndexPath source: NSIndexPath, toIndexPath destination: NSIndexPath) {
  let person = crew.removeAtIndex(source.item)
  crew.insert(person, atIndex: destination.item)

UICollectionViewController's new property called installsStandardGestureForInteractiveMovement defaults to true, so once we implement delegate function above, we're good to go.

To customize things further, we'll need to manually call UICollectionView's new interactive movement functions. Let's look at a very rough idea of how we might make the picked up cell "hover" and the others "wiggle" like iOS's home screen.

func longPressed(gesture: UILongPressGestureRecognizer) {
  let location = gesture.locationInView(collectionView)
  movingIndexPath = collectionView.indexPathForItemAtPoint(location)

  switch(gesture.state) {
  case .Began:
    guard let indexPath = movingIndexPath else { break }
    setEditing(true, animated: true)
  case .Changed:
  case .Ended:
    movingIndexPath = nil
    movingIndexPath = nil

override func setEditing(editing: Bool, animated: Bool) {
  super.setEditing(editing, animated: true)

We'll also start/stop wiggling when we dequeue cells. Lastly, we'll apply the same changes that are in animatePickingUpCell to the cell's layout attributes. To do this we can subclass UICollectionViewFlowLayout and override layoutAttributesForInteractivelyMovingItemAtIndexPath.

After all that's done, this is the outcome:

Here's a direct link to this example video, just in case.

Download the project at j.mp/bite104 to see a complete working example.