views:

281

answers:

2

Hello,

I am using following method in my application:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
     cell.contentView.backgroundColor = [UIColor lightGrayColor];
     cell.contentView.alpha = 0.5;
    }
}

When I run the application I have 7 rows in my table. According to above function only the cell of first row (row number 0) should be formatted (because of the if condition).

Cell of 1st row (row number 0) is formatted properly (as per desired output). But if I scroll the table down one more cell is displayed as formatted: cell at row number 5.

Why so?

+4  A: 

I think the reason is that TableView reuses already existing cells and displays them if it is possible. What happens here - when table is scrolled and row 0 becomes invisible then itscorresponding cell is used for a newly displayed row. So if you're reusing cells you must reset their properties:

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 
   if(indexPath.row == 0) { 
       cell.contentView.backgroundColor = [UIColor lightGrayColor];  
       cell.contentView.alpha = 0.5; } 
   else
   {
    // reset cell background to default value
   }
}
Vladimir
+3  A: 

I agree with Vladimir's answer. However, i also believe you should follow a different approach.

In the current situation you are formatting your cell frequently, as the method gets called in each scroll, and this leads you to a suboptimal performance.

A more elegant solution is to format 1st row differently than others only "once" : when you create your cells.

    // Customize the appearance of table view cells.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *CellIdentifier;
        if(indexPath.row == 0)
        CellIdentifier = @"1stRow";
        else
        CellIdentifier = @"OtherRows";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell==nil) { 
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            if(indexPath.row == 0){
          cell.contentView.backgroundColor = [UIColor lightGrayColor];  
          cell.contentView.alpha = 0.5;
                 // Other cell properties:textColor,font,...
            }
            else{
          cell.contentView.backgroundColor = [UIColor blackColor];  
          cell.contentView.alpha = 1;
          //Other cell properties: textColor,font...
            }

        }
        cell.textLabel.text = .....
        return cell;
    }
ahmet emrah