Adding a loading indicator to your infinite UICollectionView
The easiest way for adding a loading indicator to your asynchronous data view in under 5 minutes without any third-party code
The Problem
When working with Restful APIs, we typically want to divide the fetched data into multiple pages and not load all data at once. As a result, we have to gradually load the data as soon as the user reached the bottom of the previously fetched data. From a UX perspective, we have to inform the user that we’re loading more results when he gets the end of UICollectionView. There are many Cocoapod libraries to show an UIActivityIndicatorView at the bottom of an UICollectionView. Still, I believe that the issue is too small and simple to fix by installing third-party libraries. Let’s tackle this without installing any Cocoapods.
The Solution
The trick here is to add a loading cell into our UICollectionView, containing the UIActivityIndicatorView (or any custom animation item) and display it as the last UICollectionViewCell. This means the cell becomes visible when the user reaches the end of the available data.
The Implementation
First, we create a custom loading cell:
Second, we change the UICollectionView delegation code as follows:
That is all! You have successfully created your own custom loading cell without using any third-party code!
Code Explanation
There are three adaptions we need to make this work.
- When returning the number of items in
numberOfItemsInSection
, we want to return one more than the data count (line 3). This cell overflowing will be our loading cell. - Next, in
cellForItemAt
we need to check whether we have reached the end of the data. If so, we return theIndicatorCell
; otherwise we return the normal cell, in this casePostCell
(lines 8 and 16 following). - The last adaption is the cell height returned from
sizeForItemAt
. This is only required to reduce the height of theIndicatorCell
(line 29).
Thanks for reading!
We are always looking for talented and passionate Swift developers! Feel free to check out our writer’s section and find out how you can share your knowledge with the Next Level Swift Community!