UICollectionViewCell拖动预览的自定义视图

时间:2018-10-24 03:34:15

标签: ios uicollectionview drag-and-drop

我正在尝试实现一项功能,该功能由用户将一个collectionview单元拖放到另一个单元上。但是,我想完全更改运动中物体的预览,以匹配我的应用程序的视觉隐喻(该物体没有移动,该物体包含的东西正在移动)。

例如,假设我的collectionview单元显示了一支猪笔,而我想让猪从一支笔移动到另一支笔,则预览视图应该是只显示一只而不是一支笔的视图。这与苹果使用其API的意图稍有不同,但我认为这是有效的。

我看过func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters,但这只是让您稍微裁剪一下,而不是重新制作整个视图。

有什么想法/想法吗?

1 个答案:

答案 0 :(得分:2)

从iOS 11开始,您可以使用UIDragItem。有一个

open var previewProvider: (() -> UIDragPreview?)?

一个简单的例子:

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]
}

在您开始拖动拖动图像周围的项目时,它将立即更改为自定义视图。

演示

在演示中,您可以看到两个UICollectionView。从上方的UICollectionView开始拖放操作,并将一个项目拖至下方的项目。随着项目的移动,将显示该项目的自定义预览。

enter image description here

您正在寻找什么吗?