UICollectionViewDiffableDataSource optional sections

703 views Asked by At

I'm trying to implement a collection view with the diffable data source. I have some optional advertisment which I would like to put in a separate section of the collection view (for specific layouting etc.). My sections look like this:

enum Section: Int, CaseIterable {
            case topSection
            case midSection
            case advertismentSection
            case bottomSection
        }

The height of the item in the advertismentSection is defined like this:

let heightDimension = NSCollectionLayoutDimension.estimated(200)

this heightDimension is then used for the group height etc.

This works fine when I add items to the advertismentSection, however, when it's empty, I would assume it should have height of 0, but it's not the case, it's 200 regardless if it's empty or not. When I try to make the height 0, I get a warning that it's invalid.

Another approach I tried is to simply not add this advertismentSection to the snapshot when I have nothing to show, but this crashes the app because the number of sections in the snapshot needs to be the same as defined in your Section enum.

How should I solve this problem?

1

There are 1 answers

0
SomuYadav On

There is two way to append section by enum:

1. snapshot.appenSections(Section.allcase)
2. snapshot.appenSections([topSection,.midSection,. bottomSection])

if you already applied snapshot and you want different sections then you have to apply new snapshot:

var snapshot = NSDiffableDataSourceSnapshot<section,row>
snapShot.appendSection([[topSection,.midSection,. bottomSection]])
dataSource.apply(snapshot)