John Doe
John Doe

Reputation: 3671

UITableView cells mixed when scrolling

While I realise this is a popular problem among developers and there are many similar questions on Stack Overflow, none have been able to help me resolve this. There is a strange issue with a UITableView in which the individual cells are becoming mixed up, or seemingly mixed up. I believe I am reusing cells correctly and simply need a second set of eyes. Here is my code:

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

    SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    cell.friendFullName.text = [users objectAtIndex:indexPath.row];

    return cell;
}

I am using dynamic, custom cells in a seperate UITableCell.

Upvotes: 0

Views: 837

Answers (1)

Joel
Joel

Reputation: 16124

You cell is being reused. Set your label in willDisplayCell instead of cellForRowAtIndexPath.

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

    SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
   SimpleTableCell *simpleTableCell = (SimpleTableCell *)cell;
   simpleTableCell.friendFullName.text = [users objectAtIndex:indexPath.row];
}

Upvotes: 5

Related Questions