Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 818
imgroot Avatar asked Jul 04 '26 10:07

imgroot


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
}
like image 136
Viktor Gavrilov Avatar answered Jul 06 '26 08:07

Viktor Gavrilov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!