UICollectionView Diffable Datasource Wrapper with Loading Indicator and Multiple Section Layouts Handling

Hasan Acar
3 min readJun 6, 2021

With SwiftUI, Apple created a really simple way to build user interfaces using declarative approach. Apple also introduced new UIKit APIs with iOS 13 to simplify UIKit implementations. Even, potential of SwiftUI is greater than creating simple user interfaces; New UIKit APIs are also helping to create interfaces as declarative as possible and it still shows a promise, IMO.

Using UICollectionViewDiffableDatasource, we easily manage the handling of datasource changes and defining multiple sections with different section layouts. Also, combining these features, we could add extra capabilities into our datasource wrapper.

I created this datasource wrapper to achieve to create collection views and its layouts with ease. Using enums, we can define sections and items for our collection view and only worry about providing cells and applying snapshots.

Let’s start to create following use case;

First define section and item enums that we want to use for this use case;

HomeSection and HomeItem enums

Secondly, we define section layouts inside our section enum; so, our wrapper uses it when it needs to provide NSCollectionLayoutSection.

DiffableDatasource redraws its content when orientation changes; So, we can add additional constraints in here to layout our UI properly. For example, following code will group its content with 2 columns on landscape mode.

Implementation of Sectionable

Thirdly, define the datasource to handle creations of cells and supplementary views.

Now, our datasource is ready to use with a little configuration on viewDidLoad.

Rest is handling the loading data and applying snapshots with those related data. Here is the final result;

You can access above implementation from this repository

Takeaways

Using UICollectionViewDiffableDatasource is straightforward. It can easily be wrapped to implement additional features on top of it and probably you will never need the UITableViewDiffableDatasource again.

Handling different section layout contents in UICollectionViewDiffableDatasource is one of the problems that you need to solve to make it reusable. I hope that this wrapper implementation can be a starting point for you to help solving it and to implement additional use cases you require.

Let me know if you have any feedbacks or comments.

Thanks for reading.

Resources

--

--