Search code examples
iosuitableviewscrollcell

iOS UITableView Cell loads incorrectly after scroll?


I'm having 2 UITableView in a view and I added the UITableViewCellAccessoryDisclosureIndicator only at the 2nd table row 5 and row 7.

But after scrolling the 2nd table down (which row 1 disappears) and then scroll back to top (which row 1 appears), row 1 now has the UITableViewCellAccessoryDisclosureIndicator?! Did row 1 somehow become row 5 or row 7??? Below is my code for cellForRowAtIndexPath:

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

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

    cell.textLabel.textColor = [UIColor blueColor];
    cell.detailTextLabel.textColor = [UIColor blackColor];
    if (tableView == table1)
    {
        cell.textLabel.text = [title1 objectAtIndex:indexPath.row];
        cell.detailTextLabel.text = [list1 objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else if (tableView == table2)
    {
        cell.textLabel.text = [title2 objectAtIndex:indexPath.row];
        cell.detailTextLabel.text = [list2 objectAtIndex:indexPath.row];
        if (indexPath.row == 5 || indexPath.row == 7)
        {
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else
        {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    return cell;
}

Thanks a lot!


Solution

  • UITableViewCells are reused to optimize performance. This happens in [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; You need to explicitly set any properties you would like on the cell at each call of tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath .

    Something like this should resolve the issue:

    if (indexPath.row == 5 || indexPath.row == 7)
            {
                cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
            else
            {
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.accessoryType = UITableViewCellAccessoryNone;
            }