简体   繁体   中英

UITableViewCell content incorrect when editing and scrolling

My tableview works perfectly fine when not in editing mode. All cells show up as expected, but if I enter editing mode and scroll, the cells that are redrawn while in editing mode have the incorrect content. In my function that turns off editing, I reload the table data and it shows up correctly again.

Here the relevant code.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath
{    
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];


FieldItemDecrypted *theField = [decryptedArray objectAtIndex:indexPath.row];




    // Configure the cell...

      cell.textLabel.text = [[NSString alloc] initWithData:theField.field encoding:NSUTF8StringEncoding];
      cell.detailTextLabel.text = [[NSString alloc] initWithData:theField.type encoding:NSUTF8StringEncoding];    


return cell;
}

And my code for editing:

- (IBAction)editRows:(id)sender
{

if ([self.tableView isEditing])
{
    [self.tableView setEditing:NO animated:YES];
    [self.tableView reloadData];
}
else
{
    [self.tableView setEditing:YES animated:YES];
}

}

Should look like this:

在此输入图像描述

but looks like this after scrolling while editing:

在此输入图像描述

You are initializing a UITableViewCell object first, then dequeuing from the table view? This is incorrect.

Try:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

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

I just tried this on a demo project and it behaves as expected.

I'm more familiar with this type of cell reuse:

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

  if (!cell) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                      reuseIdentifier:nil];
  }
  FieldItemDecrypted *theField = [decryptedArray objectAtIndex:indexPath.row];
  // Configure the cell...

  cell.textLabel.text = [[NSString alloc] initWithData:theField.field encoding:NSUTF8StringEncoding];
  cell.detailTextLabel.text = [[NSString alloc] initWithData:theField.type encoding:NSUTF8StringEncoding];    


  return cell;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM