Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom View for UICollectionViewCell Drag Preview

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?

like image 226
Sam Jarman Avatar asked Oct 24 '18 03:10

Sam Jarman


1 Answers

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.

enter image description here

Is that what you are looking for?

like image 154
Stephan Schlecht Avatar answered Nov 02 '22 00:11

Stephan Schlecht