以编程方式将UITableView行从一个位置移动到另一个位置

我有一个UITableView,我想以编程方式将一行从位置N1移动到位置N2,我希望它从旧位置动画到新位置。 我查看了UITableView文档,我只看到了插入,重新加载和删除。 你知道我可以通过编程方式做到这一点吗?

几个笔记:

  • 我知道我可以从位置N1动画删除动画并同时将插入动画设置到位置N2。 这是我的后备,但我希望用户明白它真的从N1转移到N2。

  • 我不是在谈论允许用户将它从一个地方拖到另一个地方。 我知道如何做到这一点,我正在寻找一种方法来以编程方式启动和动画移动。

我过去曾经处理过类似的事情,解决方案并不漂亮,但确实有效。

基本上你必须做一些数学来计算屏幕上行的位置。 然后根据UITableViewcontentOffsety属性进行调整。

你可以这样做:

 [myView convertPoint:localPosition toView:nil]; 

然后你将构建一个与你的视图相同的新UIView 。 将其框架设置为您正在尝试移动的UITableViewCell顶部。 将其添加为应用主UIWindow的子视图。

所有这一切都要在你的UITableView上设置userInteractionEnabled或者scrollEnabledNO ,这样用户就不会在整个过程中scrollEnabled事物的位置(只要记住在完成所有事情时将其设置回YES动画)。

然后将其设置为新位置然而最有意义。

我知道您可能需要在所有这些过程中滚动UITableView ,这会使事情变得相当复杂,但您也可以为该滚动设置动画。

如果您的应用中有必要,您当然必须在您正在设置动画的行上执行类似的操作。

就像我说它不容易或漂亮。 但我确实理解你要完成的任务,我认为当它正确拉开时效果非常棒。

如果有人更好地了解如何在不疯狂的情况下解决这个问题,我很乐意知道,但这种类型的实施是我能做到的最好的。

 [table beginUpdates]; [table moveRowAtIndexPath:indexPath toIndexPath:destIndexPath]; [table endUpdates]; 

如果您使用的是iOS 5或hight,则可以使用以下方法:

 - (void)moveRowAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath 

例如:

 //move last cell one row up. NSIndexPath *oldPath = [NSIndexPath indexPathForRow:[items count] - 1 inSection:0]; NSIndexPath *newPath = [NSIndexPath indexPathForRow:[items count] - 2 inSection:0]; [[self tableView] moveRowAtIndexPath:oldPath toIndexPath:newPath]; 

在这里查看apple的文档。

我想你最好的后备确实是删除和插入方法,如:

 [tableView beginUpdates]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:oldPath] withRowAnimation:UITableViewRowAnimationLeft]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newNewPath] withRowAnimation:UITableViewRowAnimationLeft]; [tableView endUpdates];