使用insertRowsAtIndexPaths时的表视图单元索引

时间:2011-11-23 01:07:14

标签: ios tableview tableviewcell

好的,我被困住了。这是我以前的一个帖子的扩展。这是我想要做的。

我在导航栏上有一个“编辑”按钮,按下该按钮会在我的一个部分表格视图的开头添加一个单元格。此单元格的目的是允许使用向表中添加新数据;因此它的编辑风格是插入。表格中的其余单元格配置为“删除”的编辑样式。

这是我的选择方法:

- (IBAction) setEditing:(BOOL)isEditing animated:(BOOL)isAnimated
{
    [super setEditing:isEditing animated:isAnimated];
    // We have to pass this to tableView to put it into editing mode.
    [self.tableView setEditing:isEditing animated:isAnimated];

  // When editing is begun, we are adding and "add..." cell at row 0.
  // When editing is complete, we need to remove the "add..." cell at row 0.
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
  NSArray* path = [NSArray arrayWithObject:indexPath];

  // fill paths of insertion rows here
  [self.tableView beginUpdates];
  if( isEditing )
   [self.tableView insertRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationBottom];
  else
   [self.tableView deleteRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationBottom];
  [self.tableView endUpdates];

  // We nee to reload the table so that the existing table items will be properly 
  // indexed with the addition/removal of the the "add..." cell
  [self.tableView reloadData];
}

我在我的代码中考虑了这个额外的单元格,除了我现在有两个索引路径= [0,0] - 新单元格和表格中原来的第一个单元格。如果我在setEditing中添加一个重新加载表视图单元格的调用,则会重新索引单元格,但现在我的表格视图不再是动画。

我想要我的蛋糕并且也吃它。还有另一种方法可以完成我想做的事情并保持动画吗?

- 约翰

1 个答案:

答案 0 :(得分:0)

您可以执行您想要的操作,但需要保持数据源与表一致。换句话说,当重新加载表时,tableView:cellForRowAtIndexPath以及负责构建表的其他UITableViewDataSourceUITableViewDelegate方法应返回相同的单元格,具体取决于您要添加/删除的编辑状态在setEditing:antimated:

因此,当您在setEditing:animated:中插入/删除单元格时,您还需要确保您的数据源反映相同的更改。如果要将特殊单元格添加到节的开头但其余数据来自数组,则这可能很棘手。一种方法是在重新加载表时,如果编辑,则将第0行设为添加单元格,并为后续单元格的数组索引使用第1行。如果你这样做,你还需要在tableView:numberOfRowsInSection:添加一个来计算额外的单元格。

另一种方法是为add单元格添加一个部分,在不编辑时将有0行,否则为1行,然后返回相应的单元格。这还需要您根据您希望的外观来配置您的表格和单元格。