迅速。使用拖放

时间:2018-04-26 22:00:26

标签: ios swift drag-and-drop uicollectionview

我现在已经停留了2周以上,如何使用新的一个集合视图中的拖放多个项目(即重新排序集合视图中的多个项目) ios11 drag&丢弃协议。我不能让细胞一致地正确重新排序。

我已经尝试过使用占位符,但这似乎更适合远程拖动到带有异步数据加载的collectionView。

我已尝试按照博客文章中的答案给出的说明

https://hackernoon.com/drag-it-drop-it-in-collection-table-ios-11-6bd28795b313

其中给出的指示(作为帖子末尾的问题列表中的答案)如下:

在同一个集合视图中重新排序多个项目有点繁琐,需要手动处理。

首先,从collectionView(_:dropSessionDidUpdate:withDestinationIndexPath :)返回时,在UICollectionViewDropProposal中使用UICollectionViewDropIntent为.move UIDropOperation指定.u /,

func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal
{
    return UICollectionViewDropProposal(operation: .move, intent:  .unspecified)
}

其次,您需要显式处理要在集合视图中重新排序的每个项目的插入和删除。例如:

let items = coordinator.items
var dIndexPath = destinationIndexPath
if dIndexPath.row >= collectionView.numberOfItems(inSection: 0)
{
  dIndexPath.row = collectionView.numberOfItems(inSection: 0) - 1
}
var sourceIndexPaths = [IndexPath]()
var destinationIndexPaths = [IndexPath]()
for item in items
{
  if let sourceIndexPath = item.sourceIndexPath
  {
    sourceIndexPaths.append(sourceIndexPath)
    destinationIndexPaths.append(dIndexPath)
    self.items2.remove(at: sourceIndexPath.row)
    self.items2.insert(item.dragItem.localObject as! String, at: dIndexPath.row)
    dIndexPath = IndexPath(row: dIndexPath.row + 1, section: 0)
  }
}
collectionView.performBatchUpdates({
  if collectionView === self.collectionView2
  {
    collectionView.deleteItems(at: sourceIndexPaths)
    collectionView.insertItems(at: destinationIndexPaths)
  }
})

这部分有效但仅当destinationIndexPath小于所有拖动项的sourceIndexPaths时,即在5个项目的collectionView中,在indexPaths 3&amp ;; 4,并将它们插入indexPath 1工作,订单是正确的。但是,如果我在indexPath 0&amp ;;中收集项目,它就会工作(某些项目会被删除,其他项目会被删除,顺序也会不正确)。 1并尝试将它们放在indexPath 4中。如果某些植绒项目的sourceIndexPaths小于destinationIndexPath而其他项目的sourceIndexPaths大于destinationIndexPath,则会更复杂。

该作者的示例项目位于

https://github.com/pgpt10/DragAndDrop-CollectionView

有谁知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

问题是如何在调用performBatchUpdates之前手动删除和插入页面时,在集合视图中计算正确的indexPath。我能够通过检查模型(collectionView中的项数组)并在每个循环中获取当前项的新indexPath来解决问题。比手动尝试计算每个删除和插入如何影响系统提供后续拖动项的索引路径

更容易