During the last week I was heavily working with UICollectionViewDiffableDataSources at work. We are currently creating an app which contains a lot of collection views which are constantly updating and changing. So diffable datasources were a perfect fit. From the UI department we got the task to implement empty state views for all of our lists. So I sat down and was searching for a way to directly bake in the empty state view inside the the diffable datasource without having the need to handle the state anywhere else. In the following I want to provide you with my findings and the code I came up with, to enhance a UICollectionViewDiffableDataSource with an empty state view.
Code
The following code block demonstrates my solution to have an empty state view directly tied to an UICollectionViewDiffableDataSource.
Explanation
Line 2: Extend the base UICollectionViewDiffableDataSource class
Line 3-4: Keep references to the UICollectionView on which the data source is applied and a potential empty state view
Line 13-21: Initialize the base class with the super.init call and set the view references
Line 23-24: Override the base class apply method with a custom one which handles the empty state view
Line 26-28: If no empty view was supplied, do not calculate anything and just return the method
Line 30: If the itemIdentifiers of the snapshot are empty, show the empty state view by activating the auto layout constraints and adding it as a subview to the collectionView, referenced in the init
Line 41: If the item itemIdentifiers of the snapshot are not empty, deactivate corresponding auto layout constraints and remove the empty state view from the superview.
Usage
The usage is rather simple. The only difference from calling the standard initializer is, that you can provide an optional UIView to be displayed when the datasource is empty.
Conclusion
With this small custom UICollectionViewDiffableDataSource class we are now able to define any UIView instance to be shown, when the datasource does not contain any items.
I hope you found this small tip useful. If you have suggestions or question don't hesitate to reach out to me !