How to handle empty state when using diffable data source - UICollectionViewDiffableDataSource?

Viewed 1077

When using traditional UICollectionView, we often use the following code to handle empty state:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if items.count == 0 {
       // Display empty view
    } else {
      // Display collection view
    }
    return items.count
}

How to approach state handling while using diffable data sources in UICollectionView or UITableView?

1 Answers

You could handle it when your are creating/updating snapshots:

func performQuery(animate: Bool) {
    var currentSnapshot = NSDiffableDataSourceSnapshot<Section, ViewCell>()
    
    if items.isEmpty {
        currentSnapshot.appendSections([Section(name: "empty")])
        currentSnapshot.appendItems([ViewCell(tag: 0, type: .empty)], toSection: Section(name: "empty"))
    } else {
        currentSnapshot.appendSections([Section(name: "items")])
        currentSnapshot.appendItems([ViewCell(tag: 1, type: .item)], toSection: Section(name: "items"))
    }
        
    dataSource.apply(currentSnapshot, animatingDifferences: animate)
}

With the code from above CollectionView will display an "Empty" cell, when items are empty, or normal "Item" cell otherwise. If you do not need to display "Empty" view, you could just append "Items" section, when items are not empty

If you want to show collection view only when there are items (and hide it otherwise), you could do something like this:

if items.isEmpty {
    collectionView.isHidden = true
    emptyView.isHidden = false
} else {
    collectionView.isHidden = false
    performQuery(animate: false)
    emptyView.isHidden = true
}
Related