我正在为Mac(10.11)创建一个简单的应用程序。我有nsCollectionView,可以对对象进行排序。我添加了拖放支持,但nsCollectionView不提供动画。相反,它会重新加载其内容。

    func collectionView(collectionView: NSCollectionView, writeItemsAtIndexes indexes: NSIndexSet, toPasteboard pasteboard: NSPasteboard) -> Bool {
        let data = NSKeyedArchiver.archivedDataWithRootObject(indexes)
        pasteboard.setData(data, forType: "business_drag")

        return true
    }


    func collectionView(collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndex proposedDropIndex: UnsafeMutablePointer<Int>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionViewDropOperation>) -> NSDragOperation {
        return NSDragOperation.Move
    }

    func collectionView(collectionView: NSCollectionView, acceptDrop draggingInfo: NSDraggingInfo, index: Int, dropOperation: NSCollectionViewDropOperation) -> Bool {

        Swift.print("acceptDrop")

        let pasteboard = draggingInfo.draggingPasteboard()
        let data = pasteboard.dataForType("business_drag")
        let indexes = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSIndexSet
        let draggedCell = indexes.firstIndex

        let old = NSIndexPath(forItem: draggedCell, inSection: 0)
        let new = NSIndexPath(forItem: index, inSection: 0)

        collectionView.animator().moveItemAtIndexPath(old, toIndexPath: new)

        // uncommenting this lines makes collectionView reload its conntent
//       let object = collectionView.content.removeAtIndex(draggedCell)
//      collectionView.content.insert(object, atIndex: index)

        return true
    }

我已经从appledeveloper portal下载了示例代码,但它是用objective-c编写的

最佳答案

你需要确保两件事:
在调用moveItemAtIndexPath之前,请确保未将当前动画上下文的持续时间更改为零(默认为0.25)。您可以使用NSAnimationContext.currentContext().duration更改该值。
确保已将Calayer添加到滚动视图(而不是集合视图)。您可以在界面生成器中打开,也可以使用wantsLayer以编程方式打开。
一个例子可以参考以下存储库,它是苹果示例项目cocoslidecollection的翻译版本,cocoslidecollection是nscollectionview 2015的演示。检查Calayer的BrowserWindow.xib
https://github.com/ooper-shlab/CocoaSlideCollection-Swift
另外,我还制作了一个视频教程,请看这个
YouTube:https://youtu.be/fEuiLhYerBA
源代码:https://github.com/harryworld/NSCollectionView-DragDrop

10-08 09:08
查看更多