0

好吧,我被困住了。这是我之前的一篇文章的延伸。这是我想要做的。

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

这是我的setediting方法:

- (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 中添加重新加载表格视图单元格的调用,单元格将重新编制索引,但现在我的表格视图不再具有动画效果。

我想要我的蛋糕,也吃掉它。有没有另一种方法来完成我想做的事情并保持动画?

- 约翰

4

1 回答 1

0

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

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

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

于 2011-12-01T17:01:53.307 回答