Rejecting a drop UICollectionView

Wed, 12/06/2017 - 15:37

I recently used an alternative solution to LXReorderableCollectionViewFlowLayout.

Apple's build in UICollectionView delegate methods for drag and drop namely

func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

Im using a UILongPressGestureRecognizer to handle the drag, but I needed a way to reject the drop's.

When you "reorder" items from one index to another, the user may drop an item in a place that is "empty". I wanted to reject this and found a pretty easy way.

In my case I'm using a UICollectionView that is full of photos. The easiest way to reject the drop is on the case .ended, check if the users destination drop is bigger than count of the items you have in your array, and if it is, cancel the interaction.

Below is an example of that!

    @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
        if pictures.count == 0 {
            return
        }
        switch(gesture.state) {
            
        case .began:
            guard let selectedIndexPath = photoCollectionView.indexPathForItem(at: gesture.location(in: photoCollectionView)) else {
                photoCollectionView.cancelInteractiveMovement()
                break
            }
            photoCollectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
        case .changed:
            photoCollectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
        case .ended:
            guard let destinationIndexPath = photoCollectionView.indexPathForItem(at: gesture.location(in: photoCollectionView)) else {
                photoCollectionView.cancelInteractiveMovement()
                break
            }
            if destinationIndexPath.item >= pictures.count {
                photoCollectionView.cancelInteractiveMovement()
                return
            }
            photoCollectionView.endInteractiveMovement()
        default:
            photoCollectionView.cancelInteractiveMovement()
            break
        }
    }

 

Add new comment