3

I have two sections in my UICollectionView. I would like to be able to drag cells within each section but not between them.

I am using a long press gesture recognizer to animate the cell drag movement so I could check that the drop location is not in a different section. Is there a way to determine a section's frame?

Or is there a simpler way?

4

1 回答 1

2

在 中UICollectionViewDropDelegate,此协议func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal可以提供帮助。

检查下面的示例,了解如何防止将项目从一个部分拖到另一部分:

UICollectionViewDragDelegate中,我们使用该itemsForBeginning函数来传递有关对象的信息。您可以看到,我将索引和项目传递给localObject

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

UICollectionViewDropDelegate中,我这样做了:

func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
    if let object = session.items.first?.localObject as? (Item, IndexPath), object.0.status, let destinationIndexPath = destinationIndexPath, object.1.section == destinationIndexPath.section {
        let itemAtDestination = sectionViewModel[destinationIndexPath.section].items[destinationIndexPath.row]
        if itemAtDestination.status {
            return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
        }
    }
    return UICollectionViewDropProposal(operation: .forbidden)
}

根据苹果

当用户拖动内容时,collection view 会重复调用这个方法来确定如果它发生在指定位置,你将如何处理它。集合视图根据您的建议向用户提供视觉反馈。在此方法的实现中,创建一个 UICollectionViewDropProposal 对象并使用它来传达您的意图。因为在用户拖动表格视图时会重复调用此方法,所以您的实现应该尽快返回。

我做了什么:我有几个限制要涵盖:

  • 防止 item.status == true 转到同一部分中的项目
  • 防止项目进入其他部分

动图 拖动样本

于 2020-08-19T11:17:13.963 回答