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 de
This is a great tutorial for changing UICollectionView section color:
http://www.ericjchapman.com/jekyll/update/ios/2014/11/10/ios-changing-section-background-color-in-UICollectionView.html
Basically, we will have to subclass UICollectionViewLayoutAttributes
, UICollectionReusableView
and UICollectionViewLayout
in order to create a instance UICollectionReusableView as section's background view.
This is his result:
Please follow the link for more details explanation.
I have changed the background color of each section in a very simple manner in the following method: But I was not sure whether it is the right thing to do. But it did work.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
FamilyCalendarCellItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"calendarItem" forIndexPath:indexPath];
Event *event;
_headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
UICollectionElementKindSectionHeader withReuseIdentifier:@"EventHeader" forIndexPath:indexPath]; //headerView is declared as property of Collection Reusable View class
if(indexPath.section==0) {
cell.backgroundColor=[UIColor orangeColor];
}
else if(indexPath.section==1) {
cell.backgroundColor=[UIColor yellowColor];
}
return cell;
}
In collection view every section can have a supplementary views, so put supplementary views for each section then set background color to supplementary views instead of section cells. I hope it will help.
One of the classic approach is to create a Custom Supplementary Kind and provide your custom view in CollectionView Section background. It will give you the ability to customize section backgrounds. Refer to https://stackoverflow.com/a/63598373/14162081
Its very simple just use this default UICollectionViewDelegate's method, it will works
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
print(indexPath.item)
let evenSectionColor = UIColor.clear
let oddSectionColor = UIColor.white
cell.contentView.backgroundColor = (indexPath.item % 2 == 0) ? evenSectionColor : oddSectionColor
}
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")
]