tom williams
tom williams

Reputation: 11

How to cancel a drag for UICollectionView?

I try to drag from one collection view to another, it works fine, except that when I long-press an item and stop there. the item becomes the drag preview version of it and won't fall back to the normal state. How can I stop the active drag?

only the method is called:

(NSArray<UIDragItem *> *)collectionView:(UICollectionView *)collectionView itemsForBeginningDragSession:(id<UIDragSession>)session atIndexPath:(NSIndexPath *)indexPath

no drop delegate methods are called. drag end method isn't called either

Upvotes: 1

Views: 1853

Answers (2)

SomuYadav
SomuYadav

Reputation: 123

You can also cancel drag events by cancelInteractiveMovement() method, this method will cancel drag events & rearrange old state and when your app is going into background or your controller is changing state, this method will cancel all the interactive movements:

collectionView.cancelInteractiveMovement()

Upvotes: 1

Lokesh SN
Lokesh SN

Reputation: 1593

AFAIK, there is no way to abruptly cancel an ongoing drag session (if that is what you desire), and I feel like it will be wrong on UX side of things too

You can however return a cancellation proposal via:

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

This is a drop-delegate method (requires your UICollectionView to conform to dropDelegate) that gets called throughout the drag session, till the item gets dropped.

If you return UICollectionViewDropProposal(operation: .cancel) on this method, the dragged cell animates back to the origin indicating cancellation. This is probably the best you can do...

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

    //Do your evaluation

    //if (evaluation requires drop cancellation){
    //    return UICollectionViewDropProposal(operation: .cancel)
    //}
    //else
    return UICollectionViewDropProposal(operation: .move) //This is the usual behaviour
}

Hope this helps, cheers!

Upvotes: 1

Related Questions