I had the same problem and I fixed it like this:
import UIKit
final class CollectionViewCompositionalLayout: UICollectionViewCompositionalLayout {
override init(sectionProvider: @escaping UICollectionViewCompositionalLayoutSectionProvider) {
weak var weakSelf: CollectionViewCompositionalLayout?
super.init { section, environment in
guard
let strongSelf = weakSelf,
let collectionView = strongSelf.collectionView,
let dataSource = collectionView.dataSource,
dataSource.collectionView(collectionView, numberOfItemsInSection: section) == 0
else {
return sectionProvider(section, environment)
}
return strongSelf.emptySectionLayout()
}
weakSelf = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CollectionViewCompositionalLayout {
private enum Constants {
static let size: CGFloat = 0.1
}
private func emptySectionLayout() -> NSCollectionLayoutSection {
let size = NSCollectionLayoutSize(
widthDimension: .estimated(Constants.size),
heightDimension: .estimated(Constants.size)
)
let item = NSCollectionLayoutItem(
layoutSize: size
)
let group = NSCollectionLayoutGroup.vertical(
layoutSize: size,
subitems: [item]
)
let emptySectionLayout = NSCollectionLayoutSection(group: group)
return emptySectionLayout
}
}
It doesn't look good but works pretty well :)