UICollectionViewDiffableDatasource Wrapper for making you to use UICollectionView with an ease
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;
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.
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
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.
Coordinator Pattern using Apple Combine Framework
Coordinator Pattern is one of the ways to implement navigation flow control on iOS applications. Coordinators make it…
Using custom initializers inside view controllers on iOS 13 or later.
PrefixUntilOutput and Custom “TakeUntil” Publisher Operators in Apple Combine Framework
Combine framework was introduced at WWDC 2019 as a new way of reactive programming on Apple platforms. It has native…