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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With