In the UICollectionViewDropDelegate
, this protocol func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal
can help with it.
Check the sample below for how I prevent an item being dragged from one section to the other section:
In UICollectionViewDragDelegate, we use the itemsForBeginning
function to pass information about the object. You can see that, I passed the index and item to the 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]
}
In UICollectionViewDropDelegate, I did this:
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)
}
According to Apple:
While the user is dragging content, the collection view calls this method repeatedly to determine how you would handle the drop if it occurred at the specified location. The collection view provides visual feedback to the user based on your proposal.
In your implementation of this method, create a UICollectionViewDropProposal object and use it to convey your intentions. Because this method is called repeatedly while the user drags over the table view, your implementation should return as quickly as possible.
What I Did:
I've a couple of restrictions to cover:
- Prevent item.status == true from going to items within the same section
- Prevent item from going to other sections
GIF
