Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In UICollectionView, I want to give the whole section a uniform background color, instead of for a single cell or for the whole collection view.

I don't see any delegate method to do that, any suggestions?

like image 222
lichen19853 Avatar asked Nov 28 '12 15:11

lichen19853


2 Answers

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") ] 
like image 75
leavez Avatar answered Sep 21 '22 14:09

leavez


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

like image 40
dangthaison.91 Avatar answered Sep 19 '22 14:09

dangthaison.91