1

在使用传统的 UICollectionView 时,我们经常使用下面的代码来处理空状态:

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

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

在 UICollectionView 或 UITableView 中使用可区分数据源时如何处理状态?

4

1 回答 1

1

您可以在创建/更新快照时处理它:

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)
}

使用上面的代码,当项目为空时,CollectionView 将显示一个“空”单元格,否则显示正常的“项目”单元格。如果您不需要显示“空”视图,则可以在项目不为空时附加“项目”部分

如果您只想在有项目时显示集合视图(否则隐藏它),您可以执行以下操作:

if items.isEmpty {
    collectionView.isHidden = true
    emptyView.isHidden = false
} else {
    collectionView.isHidden = false
    performQuery(animate: false)
    emptyView.isHidden = true
}
于 2021-08-07T09:38:00.043 回答