I have a UICollectionView that uses a custom subclass of UICollectionViewFlowLayout to make the section headers stick to the top of the screen while scrolling just like UITableV
I had the same issue although in my case with a custom layout. My solution was to call:
on the collectionView as appropriate to ensure that dataSource and layout are aware of the same number of items.
My layout is based on the data returned from:
super.layoutAttributesForElements(in: rect)
which was not returning the expected number of items that the dataSource indicated.
The documentation for insertItems seems to corroborate this:
Call this method to insert one or more new items into the collection
view. You might do this when your data source object receives data for
new items or in response to user interactions with the collection view.
The collection view gets the layout information for the new cells as
part of calling this method.