在iOS表视图中,如何将行移动到新部分?

我有一个表视图,在一个部分中有两行,即

--- Row A Row B 

如果我想将第1行设置为新部分的动画,即最终结果为:

 --- Row B --- Row A 

应该如何实现? 我已经尝试过的是:

 [self.tableView beginUpdates]; [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow: 0 inSection: 0]] withRowAnimation:UITableViewRowAnimationNone]; [self.tableView insertSections:[NSIndexSet indexSetWithIndex: 1] withRowAnimation:UITableViewRowAnimationNone]; [self.tableView endUpdates]; 

但是,至少在iOS 8中,该行会动画,但是新的部分是未渲染的(即白色,没有底行边框),直到某些东西触发重绘并返回之后。

 [self.tableView beginUpdates]; [self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] toIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]]; [self.tableView endUpdates]; 

这引发了一个例外:

 Invalid update: invalid number of sections. The number of sections contained in the table view after the update (2) must be equal to the number of sections contained in the table view before the update (1), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted). 

和:

 [self.tableView beginUpdates]; [self.tableView insertSections:[NSIndexSet indexSetWithIndex: 1] withRowAnimation:UITableViewRowAnimationNone]; [self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] toIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]]; [self.tableView endUpdates]; 

这引发了例外:

 cannot move a row into a newly inserted section (1) 

我应该根本没有动画并重新加载整个桌子吗?

您需要分两步执行此操作。

首先,您需要添加该部分; 您需要告诉您的数据源以考虑新部分。 对于像你这样的简单例子,你可以设置一个变量:

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { if(hasTwoSections) return 2; return 1; } 

然后在你想要触发动画的地方,调用:

 hasTwoSections = true; // this needs to be set before endUpdates [self.tableView beginUpdates]; [self.tableView insertSections:[NSIndexSet indexSetWithIndex: 1] withRowAnimation:UITableViewRowAnimationAutomatic]; [self.tableView endUpdates]; 

此时,tableView将调用数据源方法以根据您的更改更新表。

添加该部分后,您可以在另一个更新块中将该行移动到该部分:

 [self.tableView beginUpdates]; [self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] toIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]]; [self.tableView endUpdates]; 

显然,您需要更新numberOfRowsInSection返回的帐户以进行更改。

虽然这是两个步骤,但它看起来会一下子发生。

我处于类似的情况,我得到的exceptioncannot move a row into a newly inserted section (1) 。 我只发现了两个解决方案。

  1. 使用reloadData()重新加载表 – 积极,没有动画
  2. 删除并插入行,代码如下:

 self.requestTableView.deleteRowsAtIndexPaths([oldIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic) self.requestTableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 

要获得能够给行移动印象的动画效果,可以在删除,插入或重新加载部分时使用UITableViewRowAnimation.Top

 self.tableView.deleteSections(toDelete, withRowAnimation: UITableViewRowAnimation.Top) self.tableView.insertSections(toInsert, withRowAnimation: UITableViewRowAnimation.Top) self.tableView.reloadSections(toReload, withRowAnimation: UITableViewRowAnimation.Top) 

使用-[UITableView moveRowAtIndexPath:toIndexPath:]