Giving certain cells different background colors and borders?

It all depends on how you determine which cells should receive it.

For example if you want every other cell to have a red background with a white border, you could do this in the cellForItemAtIndexPath:

// This changes the cell to w/e you want it to look like
if indexPath.row % 2 == 0 {
    cell.backgroundcolor = UIColor.redColor()
    cell.layer.cornerRadius = 5.0
    cell.layer.masksToBounds = true
    cell.layer.borderColor = UIColor.whiteColor.CGColor()
    cell.layer.borderWidth = 2.0
}
//Because I don't reset the state of the cell in this branch of the if statement, 
//before I update it, this cell could have the white border color, or it could have 
//the green border that is the default. This is all due to the view reusing cells.
// also don't forget to reset the corner radius / masks to bounds, forgetting to do 
//this, will lead to some cells having a corner radius and some not.
else if indexPath.row % 3 == 0 {
    cell.backGroundColor = UIColor.blueColor()
    cell.layer.cornerRadius = 0.0
    cell.layer.masksToBounds = false
}
//this resets the cell to its original state
else {
    cell.backGroundColor = UIColor.whiteColor()
    cell.layer.cornerRadius = 0.0
    cell.layer.masksToBounds = false
    cell.layer.borderColor = UIColor.greenColor.CGColor()
    cell.layer.borderWidth = 2.0
}

But in reality the check in the if statement could be anything, just make sure when you’re reusing cells that you reset the state of the cell to its original state, before you go and modify it again.

Leave a Comment