3

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?

imgroot
  • 131
  • 3
  • 11

1 Answers1

1

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
}
Viktor Gavrilov
  • 830
  • 1
  • 8
  • 13
  • Thanks, Viktor. Just one question, Is it required to add appendSections and appendItems code, when there are no items? Can't I just put display empty view(in place of collectionView) code there? – imgroot Aug 07 '21 at 10:37
  • @imgroot you do not need to add sections when there are no items. I assumed that you want to show a different ("empty") view for such case. If you need to show a separate empty view outside of collection view, you need to do it outside of collectionView methods - I've edited my answer and added a code for a such case – Viktor Gavrilov Aug 07 '21 at 11:05
  • Thanks for your reply. But where to place that hide/show code? Because you said place it away from collectionView methods. – imgroot Aug 07 '21 at 12:06
  • It depends on the workflow of the view. You could place in didSet for your items, so the view is updated each time there is a change in items – Viktor Gavrilov Aug 07 '21 at 12:40