iOS swift 4.2 How to reject or disallow a drop into a UICollectionView

875 views Asked by At

I am trying to enable drag and drop within my app as a mechanism for triggering a function. I have a TableView that displays a list of users and I have a collectionView that can display 3 distinct types of data - but only 1 type at a time.

I want the collectionView to accept the "drop" from the tableView when it is displaying Type1 data and Type3 data, but not for Type2 data. Right now, my drag and drop is working - but it is working for all 3 data types and I don't want it to work for Type2 data.

So currently, the action I trigger just ignores the dropped data if it is displaying Type2 data - but I would like to prevent the CollectionView from even accepting it (if possible). I don't want the users to see the visual indication that a drop is possible.

I suspect that I should be using the dropProposal for this - but after reading the Apple docs and multiple hours of searching with Google and YouTube for examples - I'm at a complete loss.

I do know I'm supposed to post my broken code here with my question, but the only thing I've even thought of to try and control this was to manipulate the collectionView.dropDelegate based on the data type I was displaying. I'm fairly confident that the correct solution will be very different - but here's what I tried:

if collectionMode != "Type2" {
  collectionView.dropDelegate = self
} else {
  collectionView.dropDelegate = nil
}

If you can help point me to the answer, please do.

2

There are 2 answers

2
dahiya_boy On

Try this,

func collectionView(_ collectionView: UICollectionView, 
        dragSessionWillBegin session: UIDragSession){

     guard if collectionMode == "Mode2" else { return }
     :
     :
     // Do stuff

}
0
Jim On

The right answer in this case was to use the collectionView(_:canHandle:) function in the UICollectionViewDropDelegate for the drop target:

func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool {
    if self.collectionMode == "Type2" {return false}
    return true
}

Apple Documentation - collectionView(_:canHandle:)

Other suggestions to add the logic to the UICollectionViewDragDelegate would prevent dragging the cell ANYWHERE - which might be an okay, and even more efficient approach in some cases - however putting the logic in the drop delegate allows for greater flexibility and the case in which there are multiple drop targets and not all of them are to be invalidated.

The correct answer to this question was provided by @Bill (Thanks!) but he posted his response as a comment, not an answer.