如何在UICollectionView拖放过程中删除“鬼”单元格,并使移动单元格不透明?

时间:2019-05-07 19:16:46

标签: swift uicollectionview drag-and-drop uikit

我正在尝试在UICollectionView中实现拖放机制,这与在快捷方式应用程序中对快捷方式的组件进行重新排序非常相似。

到目前为止,这种行为是,当您开始拖动时,会留下一个透明的单元格视图,而该单元格的另一个透明视图是用手指移动的。

我想摆脱“鬼”细胞,并使移动的细胞完全不透明。

这是我的拖放行为(主要来自this post

func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    let item = itemData[indexPath.item]
    let itemProvider = NSItemProvider(object: item.title as NSString)
    let dragItem = UIDragItem(itemProvider: itemProvider)
    dragItem.localObject = item


    return [dragItem]
}

func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {

    if collectionView.hasActiveDrag {
        return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
    }

    return UICollectionViewDropProposal(operation: .forbidden)
}

func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {

    var destinationIndexPath: IndexPath
    if let indexPath = coordinator.destinationIndexPath {
        destinationIndexPath = indexPath
    }
    else {
        let row = collectionView.numberOfItems(inSection: 0)
        destinationIndexPath = IndexPath(row: row - 1, section: 0)
    }

    reorderItems(coordinator: coordinator, destinationIndexPath: destinationIndexPath, collectionView: collectionView)

}

fileprivate func reorderItems(coordinator: UICollectionViewDropCoordinator,
                              destinationIndexPath: IndexPath,
                              collectionView: UICollectionView) {

    if let item = coordinator.items.first,
        let sourceIndexPath = item.sourceIndexPath {

        collectionView.performBatchUpdates({
            self.itemData.remove(at: sourceIndexPath.item)
            self.itemData.insert(item.dragItem.localObject as! PlanItem, at: destinationIndexPath.item)

            collectionView.deleteItems(at: [sourceIndexPath])
            collectionView.insertItems(at: [destinationIndexPath])
        }, completion: nil)

        coordinator.drop(item.dragItem, toItemAt: destinationIndexPath)
    }
}

Here's an image describing what I want

1 个答案:

答案 0 :(得分:0)

不确定问题是否仍然存在,但是如果是这样: 这是处理单元格拖动状态的方法:

Is there a method to check the UICollectionView item drag cancellation if the item wasn't moved?

只需通过DispatchQueue.main.async {}

将其隐藏即可

,然后再次显示为.none状态。为我工作:)