Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cell.backgroundColor question

I found this handy code on the internet,

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
 cell.backgroundColor = (indexPath.row%2)?[UIColor grayColor]:[UIColor clearColor];
 }

I know that it makes every row a gray, then clear, then gray sort of pattern. But I want to switch off between a light gray and a dark gray. How can I modify the above code so I can switch between those two colors?

Thanks!

like image 475
SimplyKiwi Avatar asked Jan 22 '26 01:01

SimplyKiwi


1 Answers

Both darkGrayColor and lightGrayColor are valid color names, so change it to the code below. All I did was change your color names.

(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = (indexPath.row%2)
        ? [UIColor lightGrayColor]
        : [UIColor darkGrayColor];
}

Explanation of how the alternating row colors work: The indexPath.row % 2 performs a modulus on the index: if it has no remainder when divided by two, the color will be lightGrayColor; otherwise, it will be darkGrayColor. I have spaced out the code a little to make it more obvious what is happening.

like image 118
Devin Burke Avatar answered Jan 26 '26 14:01

Devin Burke