How to add a background color to a cell or section in a UICollectionView
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
Images Added smaller image Mar 3, 2016
SCSectionBackground.xcodeproj
SCSectionBackground Storyboard fix + license + read Mar 3, 2016
SCSectionBackgroundTests First commit Feb 28, 2016
SCSectionBackgroundUITests First commit Feb 28, 2016
LICENSE Storyboard fix + license + read Mar 3, 2016
README.md Update README.md Mar 3, 2016

README.md

UICollectionView section background

This project shows how to apply colour to background sections (or cells) on a UICollectionView. The code is written in Swift, and inspired by Eric Chapman's article (Objective-C GitHub project). You can apply different colours according to the NSIndexPath of the cells. Here is an example of a UICollectionView 4 sections, 3 cells with green background on the even sections and 7 cells on a blue background on the odd ones.

Section Background in UICollectionView

How does it work?

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

class SCSBCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes { 
    var color: UIColor = UIColor.whiteColor()

    override func copyWithZone(zone: NSZone) -> AnyObject {
        let newAttributes: SCSBCollectionViewLayoutAttributes = super.copyWithZone(zone) as! SCSBCollectionViewLayoutAttributes
        newAttributes.color = self.color.copyWithZone(zone) as! UIColor
        return newAttributes
    }
}
class SCSBCollectionReusableView : UICollectionReusableView {
    override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes) {       
        super.applyLayoutAttributes(layoutAttributes)
        let scLayoutAttributes = layoutAttributes as! SCSBCollectionViewLayoutAttributes self.backgroundColor =         scLayoutAttributes.color
    }
}

How to use it?

All this happens in the UICollectionViewFlowLayout used on your UIcollectionView. Here is an example of layoutAttributesForElementsInRect:

// Create decoration attributes
let decorationAttributes = SCSBCollectionViewLayoutAttributes(forDecorationViewOfKind: "sectionBackground", withIndexPath: attr.indexPath)
// Set the color(s)
if (attr.indexPath.section % 2 == 0) {
    decorationAttributes.color = UIColor.greenColor().colorWithAlphaComponent(0.5)
} else {
    decorationAttributes.color = UIColor.blueColor().colorWithAlphaComponent(0.5)
}

You will find all the details in the SectionBackgroundFlowLayout.swift file and if you want more details, please have a look at my the article I've written about it: How to create a Section Background in a UICollectionView in Swift.

Contact

You can ping me on Twitter @cath_schwz, open an issue on GitHub or leave a comment on my blog :)