NSCollectionView动画重新布局

时间:2015-11-25 06:04:24

标签: swift macos animation drag-and-drop nscollectionview

我正在为Mac创建一个简单的应用程序(10.11)。我有NSCollectionView,在其上将对对象进行排序。我添加了Drag& Drop支持,但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

编写的

1 个答案:

答案 0 :(得分:2)

您需要确定两件事:

  1. 在调用moveItemAtIndexPath之前,请确保没有将当前动画上下文的持续时间更改为零(默认情况下为0.25)。您可以使用NSAnimationContext.currentContext().duration

  2. 更改值
  3. 确保已将CALayer添加到滚动视图(不是“收藏视图”)。您可以在Interface Builder中打开,也可以使用wantsLayer

  4. 以编程方式打开

    示例可以参考以下存储库,它是Apple Sample Project的翻译版本CocoaSlideCollection,它是NSCollectionView 2015的演示。检查BrowserWindow.xib是否为CALayer。

    https://github.com/ooper-shlab/CocoaSlideCollection-Swift

    此外,我已经创建了一个视频教程,在这个

    上查看19'30“

    Youtube:https://youtu.be/fEuiLhYerBA

    源代码:https://github.com/harryworld/NSCollectionView-DragDrop