Skip to content

Instantly share code, notes, and snippets.

@keighl
Created January 2, 2013 22:21
Show Gist options
  • Save keighl/4438822 to your computer and use it in GitHub Desktop.
Save keighl/4438822 to your computer and use it in GitHub Desktop.
Alternating UITableViewCell Background Colors
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"VenueCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
cell.backgroundView = [[UIView alloc] init];
}
UIColor *evenColor = [UIColor lightGrayColor];
UIColor *oddColor = [UIColor lightGrayColor];
cell.backgroundView.backgroundColor = (indexPath.row % 2) ? evenColor : oddColor;
cell.textLabel.backgroundColor = (indexPath.row % 2) ? evenColor : oddColor;
cell.detailTextLabel.backgroundColor = (indexPath.row % 2) ? evenColor : oddColor;
Venue *venue = (Venue *)[self.venues objectAtIndex:indexPath.row];
cell.textLabel.text = venue.name;
if (venue.category != nil)
cell.detailTextLabel.text = venue.category;
return cell;
}
@nnorris7
Copy link

Hi Keighl,

A couple of comments on your code.

  1. Both your UIColors are the same, so you won't see any difference between the rows. While this may be on purpose, it could be confusing to others.
  2. You have your even and odd rows swapped. I'm sure this was a small oversight but the value following the "?" in the " ? : " operator is true, thus occurs when the conditional evaluates to 1. The % (modulo) operator returns the remainder, so...

Update:
[Ah, I just realized you are probably assuming the first row in the table (for the user anyway) is row 1, not row 0, hence why you set up your even/odd the way you did. Sorry about that!]

Again, you probably noticed this but I wanted to make sure. Thanks for posting.

Norm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment