Custom View for UICollectionViewCell Drag Preview

泄露秘密 提交于 2020-12-30 00:03:32

问题


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?


回答1:


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?



来源:https://stackoverflow.com/questions/52960717/custom-view-for-uicollectionviewcell-drag-preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!