2015-11-25 129 views
1

我正在爲Mac(10.11)創建一個簡單的應用程序。我有NSCollectionView,其中一個將排序對象。我添加了Drag &刪除支持,但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門戶網站,但它是用Objective-C

+0

對不起已故的答覆,這蘋果示例代碼你指的是? –

回答

1

兩件事情,你將需要確保:

  1. 在致電moveItemAtIndexPath,使確定您沒有將當前動畫上下文的持續時間更改爲零(默認情況下它是0.25)。您可以使用NSAnimationContext.currentContext().duration

  2. 確保您已將CALayer添加到滾動視圖(而不是集合視圖)。您可以在Interface Builder中打開或以編程方式使用wantsLayer

一個例子可以參照下面的倉庫,這是蘋果示例項目,CocoaSlideCollection,這是2015年NSCollectionView檢查演示的翻譯版本CALayer的BrowserWindow.xib

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

此外,我創建了一個視頻教程,檢查19'30" 這個

的Youtube:https://youtu.be/fEuiLhYerBA

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