简体   繁体   中英

UICollectionViewDiffableDataSource optional sections

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM