I'm trying to implement a feature where by a user drags and drops one collectionview cell onto another. However, I want to change the preview of the thing in motion completely, as to match the visual metaphor of my app (the item isn't moving, something the item contains is moving).
For example, say my collectionview cell shows a pen of pigs, and I want to to let the pig move from one pen to another, the preview view should be a view showing a single, not the pen. Its a slightly different use to what apple intended with their API, but a valid one I think.
I've seen func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters
but that just lets you clip it slightly, not re-do the whole view.
Any ideas?/Thoughts?
Since iOS 11 you can make use of UIDragItem. There is a
open var previewProvider: (() -> UIDragPreview?)?
A simple example:
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem]
{
...
let dragItem: UIDragItem = ....
dragItem.localObject = item
dragItem.previewProvider = { () -> UIDragPreview? in
let imageView = UIImageView(image: UIImage(named: "preivewOfThingInMotion"))
imageView.frame = CGRect(x: 0, y: 0, width: 64, height: 64)
return UIDragPreview(view: imageView)
}
return [dragItem]
}
As soon as you start dragging an item around the drag image will be changed to your custom view.
Demo
In the demo you can see two UICollectionViews. A drag & drop operation is started from the upper UICollectionView and an item is dragged to the lower one. As the item moves, a custom preview of the item is displayed.
Is that what you are looking for?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With