How to change background color of a whole section in UICollectionView? How to change background color of a whole section in UICollectionView? ios ios

How to change background color of a whole section in UICollectionView?


The new UICollectionViewCompositionalLayout introduced in iOS 13 have a property named decorationItems for adding decoration items conveniently, which you could use to add a background for the section.

let section = NSCollectionLayoutSection(group: group)section.decorationItems = [   NSCollectionLayoutDecorationItem.background(elementKind:"your identifier")]


The idea is to override UICollectionViewLayoutAttributes to add a color attribute. And then override UICollectionReusableView apply the color to the view background.

https://github.com/strawberrycode/SCSectionBackground


I haven't tried this out yet, but it looks to me that you need to use decoration views if you want a background behind your cells (like the shelf in the Books app). I think you should be able to have different views for each section, and set them up using the delegate method layoutAttributesForDecorationViewOfKind:atIndexPath:.