Change Cell Background Every 5 Cells

Hello I want to change the color of my UITableView Cells ever 5 cells, so I would have green for cell one blue for cell two and so on. Then once I hit 5 cells, I want the colors to start over.

This is what I have so far:

if(indexPath.row % 5 == 0){
    cell.backgroundColor = [UIColor blackColor];
} else  if (indexPath.row % 4 == 0) {
   cell.backgroundColor = [UIColor redColor];
} else  if (indexPath.row % 3 == 0) {
    cell.backgroundColor = [UIColor greenColor];
} else  if (indexPath.row % 2 == 0) {
    cell.backgroundColor = [UIColor blueColor];
} else if(indexPath.row % 1 == 0) {
    cell.backgroundColor = [UIColor orangeColor];

If someone could point me in the right direction I would really appreciate it. Thank you!

Answers


I think this is what you're looking for:

if(indexPath.row % 5 == 0)
{
    cell.backgroundColor = [UIColor blackColor];
}
else  if (indexPath.row % 5 == 1)
{
   cell.backgroundColor = [UIColor redColor];
}
else  if (indexPath.row % 5 == 2)
{
    cell.backgroundColor = [UIColor greenColor];
}
else  if (indexPath.row % 5 == 3)
{
    cell.backgroundColor = [UIColor blueColor];
}
else if(indexPath.row % 5 == 4)
{
    cell.backgroundColor = [UIColor orangeColor];
}

You want to keep the modulus divisor the same -- its the remainder that is actually going to be changing


You need to modulo against the same number, not different numbers. This should point you in the right direction:

static NSArray* rowColors;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    rowColors = @[[UIColor redColor], [UIColor blueColor], [UIColor greenColor], [UIColor orangeColor], [UIColor yellowColor]];
});

int rowMod = indexPath.row % rowColors.count;

UIColor* color = rowColors[rowMod];

cell.contentView.backgroundColor = color;

This approach does a few things better than your current approach:

  • It performs % against the same number, which is the core logic problem in what you posted
  • It dynamically uses rowColors.count, in case you want to add extra colors (e.g., change every 7 rows instead of every 5)
  • It uses an array so you don't have if/else-if/else-if/else-if getting out of control
  • It sets backgroundColor on cell.contentView instead of cell, which is the proper way to set a background color
  • The array is static and only written to once, to ensure good performance and not result in a ton of memory allocation each time you setup a cell

Hope it helps!


Need Your Help

At what point does memory allocated by malloc get a type?

c++ memory-management malloc language-lawyer

This question asks what is the dynamic type of the object allocated by malloc and according to the top answer:

Setting variable to NULL after free

c coding-style malloc free heap-memory

In my company there is a coding rule that says, after freeing any memory, reset the variable to NULL. For example ...