Search code examples
iosuitableviewsetediting

UITableView in editing mode doesn't show insertion unless reloadData called, which kills the animation


I have a UITableView with three sections, the second section has the table that shows insertion and deletion indicators in editing mode. I'm adding a cell for the insertion row in cellForRowAtIndexPath: when editing is YES. Also, when the table goes in to editing mode I reduce the number of sections so the third section doesn't show (it has a button in it that I want to hide when in editing mode). Unless I call [self.tableView reloadData] in setEditing I don't see the insertion row, but when I do call it there is no animation. What am I doing wrong?

- (void)setEditing:(BOOL)flag animated:(BOOL)animated

{
  [super setEditing:flag animated:YES];
  [self.tableView setEditing:flag animated:YES];
  //unless i add [self.tableView reloadData] i don't see the + row, but then there is no animation
  [self.tableView reloadData];

To determine number of sections I am doing this

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.editing ? 2 : 3;
}

To add the insertion row I am doing this in cellForRowAtIndexPath

 if (indexPath.row == [[[self recipe] tasks] count])
 {
    cell.textLabel.text = @"Add task...";
    cell.detailTextLabel.text = @"";

Any help greatly appreciated. I'm embarrassed to say how much time I've wasted on this!


Solution

  • You need to use UITableView's update methods. Check out Apple's comprehensive guide on the subject for more details, but this code snippet should give you an idea. Note that you should do the opposite when your table view leaves editing mode.

    NSIndexPath *pathToAdd = [NSIndexPath indexPathForRow:self.recipe.tasks.count section:SECTION_NEEDING_ONE_MORE_ROW];
    NSIndexSet *sectionsToDelete = [NSIndexSet indexSetWithIndex:SECTION_TO_DELETE];
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:@[ pathToAdd ] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView deleteSections:sectionsToDelete withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];