我一直在寻找 NSTableViewmoveRowAtIndex:toIndex 对表中的行进行动画处理的方法。据我所知,这对于排序并没有多大帮助。我对其工作原理的解释是,如果我想将第 0 行移动到第 4 行,那么中间的行就会得到适当的处理。但是,如果我有一个带有数组支持的表视图,然后对数组进行排序,我希望表视图从旧状态动画到新状态。我不知道哪些项目是移动的,哪些是为了容纳移动的项目而移动的。

例子:

[A,B,C,D] --> [B,C,D,A]

我知道第 0 行移至第 3 行,所以我会说 [tableView moveRowAtIndex:0 toIndex:3]. 。但是如果我对 [A,B,C,D] 应用一些自定义排序操作​​以使其看起来像 [B,C,D,A],我实际上不知道第 0 行移动到第 3 行而不是第 1 行、2 和 3 移动到第 0、1 和 2 行。我认为我应该能够指定所有的移动(第 0 行移动到第 4 行,第 1 行移动到第 0 行等),但是当我尝试这样做时,动画看起来不正确。

有一个更好的方法吗?

编辑:我发现 这个网站, ,这似乎做了我想做的事情,但对于应该简单的事情来说似乎有点太多了(至少我认为它应该很简单)

有帮助吗?

解决方案

moveRowAtIndex:toIndex 的文档:说,“更改在发送到表时逐渐发生”。

从 ABCDE 到 ECDAB 的转变可以最好地说明“增量”的重要性。

如果只考虑初始和最终索引,它看起来像:

E: 4->0
C: 2->1
D: 3->2
A: 0->3
B: 1->4

但是,当增量执行更改时,“初始”索引可能会在您转换数组时跳转:

E: 4->0 (array is now EABCD)
C: 3->1 (array is now ECABD)
D: 4->2 (array is now ECDAB)
A: 3->3 (array unchanged)
B: 4->4 (array unchanged)

基本上,您需要逐步告诉 NSTableView 需要移动哪些行才能到达与排序数组相同的数组。

这是一个非常简单的实现,它采用任意排序的数组并“重放”将原始数组转换为排序数组所需的移动:

// 'backing' is an NSMutableArray used by your data-source
NSArray* sorted = [backing sortedHowYouIntend];

[sorted enumerateObjectsUsingBlock:^(id obj, NSUInteger insertionPoint, BOOL *stop) {

  NSUInteger deletionPoint = [backing indexOfObject:obj];

  // Don't bother if there's no actual move taking place
  if (insertionPoint == deletionPoint) return;

  // 'replay' this particular move on our backing array
  [backing removeObjectAtIndex:deletionPoint];
  [backing insertObject:obj atIndex:insertionPoint];

  // Now we tell the tableview to move the row
  [tableView moveRowAtIndex:deletionPoint toIndex:insertionPoint];
}];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top