Resolved: UICollectionView: remove separators for specific cells only

In this post, we will see how to resolve UICollectionView: remove separators for specific cells only

Question:

I need to show separators for every cell in UICollectionView except every first cell of a section. I’m using list layout. So far I have only been able to remove all separators using configuration.showsSeparators = false.
My UICollectionView configuration:
Cell registartion:

Best Answer:

UICollectionLayoutListConfiguration has a handler closure which allows you to configure the separator appearance on an item-by-item basis: itemSeparatorHandler (https://developer.apple.com/documentation/uikit/uicollectionlayoutlistconfiguration/3727737-itemseparatorhandler).
If you don’t want bottom separators for the first item in each section you can add a handler to your UICollectionLayoutListConfiguration that hides the separator for the first item:
It looks like showsSeparators defaults to true for the grouped appearance so you don’t need to explicitly set that.
If you also want to remove the top separator you can easily do that too by adjusting topSeparatorVisibility in the handler in the same way.

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com