4

In my app i am using one table.Now i want to separate two rows by alternate colors.That means my first row will have white color,my second row will have gray color third will have again white color likewise...So please anyone have solution for it.Then please share it.Thanks in advance.

Akshay

Akshay Aher
  • 2,525
  • 2
  • 18
  • 33

2 Answers2

10

Here is a relatively simple implementation:

In your tableViewController implement the cellForRow with something like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"DefaultCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // check if row is odd or even and set color accordingly
    if (indexPath.row % 2) {
        cell.backgroundColor = [UIColor whiteColor];
    }else {
        cell.backgroundColor = [UIColor lightGrayColor];
    }

    return cell;
}
Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
Chris
  • 403
  • 3
  • 6
  • when first display 10 row it's show proper according to condition but when we scroll down it mesh all the cell colour and not working as per calculation,not working when coming dynamic data in uitableview . – Darshan Feb 24 '14 at 11:51
1

The up-voted answer is not precise. On iOS6, the background color of contentView needs to be set instead:

// check if row is odd or even and set color accordingly
if (indexPath.row % 2) {
    cell.contentView.backgroundColor = [UIColor whiteColor];
}else {
    cell.contentView.backgroundColor = [UIColor lightGrayColor];
}
bizz84
  • 1,964
  • 21
  • 34