Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with empty items section in UICollectionView CompositionalLayout

I'm trying to make collection view with compositional layout which have multi sections

but if there is empty items in sections how can I deal with it?

if item is empty I don't want to show that section

UICollectionViewCompositionalLayout { (section, env) -> NSCollectionLayoutSection? in
  // do I have to code in this area? 
}

enter image description here

like image 279
PrepareFor Avatar asked Oct 15 '25 05:10

PrepareFor


1 Answers

If you are also using UICollectionViewDiffableDataSource, you could deal with empty sections when you are creating/updating your snapshots - append only sections with items in it.

In my project I do something like this:

func performQuery(animate: Bool) {
    var currentSnapshot = NSDiffableDataSourceSnapshot<Section, ViewCell>()
    
    if !calendars.isEmpty {
        currentSnapshot.appendSections([Section(name: "main")])
        currentSnapshot.appendItems(calendars, toSection: Section(name: "main"))
    }

    if !lifeCals.isEmpty {
        currentSnapshot.appendSections([Section(name: "life")])
        currentSnapshot.appendItems(lifeCals, toSection: Section(name: "life"))
    }
    
    dataSource.apply(currentSnapshot, animatingDifferences: animate)
}

This way in case user has 0 life calendars, there will be no "life" section.

like image 188
Viktor Gavrilov Avatar answered Oct 17 '25 20:10

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!