UICollectionViewDiffableDatasource Wrapper for Handling Multiple Section Layout and more…
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…