2017-02-19 110 views
0

我想使用拖放委託方法在NSCollectionView內移動項目。我得到它的工作,直到項目應該下降。沒有目標指示器(間隙),當釋放鼠標時,該項目反彈。代表validateDropacceptDrop永遠不會被調用。該CollectionViewItems的數據顯示,從自定義對象:在NSCollectionView內拖放示例

enter image description here

func collectionView(_ collectionView: NSCollectionView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool { 

    print("canDragItem", indexPaths) 
    return true 
} 

func collectionView(_ collectionView: NSCollectionView, writeItemsAt indexPaths: Set<IndexPath>, to pasteboard: NSPasteboard) -> Bool { 

    let indexData = Data(NSKeyedArchiver.archivedData(withRootObject: indexPaths)) 
    pasteboard.declareTypes(["my_drag_type_id"], owner: self) 
    pasteboard.setData(indexData, forType: "my_drag_type_id") 

    print("write data", indexData) 
    return true 
} 


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

    print("validation") 
    return NSDragOperation.move 
} 

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

    let pb = NSPasteboard() 
    let indexData = (pb.data(forType: "my_drag_type_id"))! as Data 
    let indexPath = (NSKeyedUnarchiver.unarchiveObject(with: indexData)) as! IndexPath 
    let draggedCell = indexPath.item as Int 

    print("acceptDrop", draggedCell) 


    return true 
} 

哎呀......我想什麼有什麼錯寫項目數據的紙板被拖動。有什麼建議麼。

+0

檢查方法的聲明。 '路徑'缺失。 – Willeke

+0

@Willeke謝謝你的迴應,但你是什麼意思?什麼路徑缺少在哪裏?謝謝! – JFS

+0

您的'validateDrop'和'acceptDrop'函數沒有正確的參數。新版本有一個'suggestedIndexPath'和'indexPath'參數。 – Willeke

回答

0

這個問題有兩種可能的原因。在這個具體情況下,Willeke的回答是正確的。實際上你仍然可以使用所有拖放代理函數的舊索引集版本,但是如果你這樣做,那麼你必須確保所有的都是舊版本,不會混淆舊的和新的!

總之,如果你canDragItems:委託函數有一個叫indexPaths參數,然後確保writeItemsAt:validateDrop:acceptDrop:功能還利用IndexPaths,不IndexSets的。

其次,在我的例子中是這種情況,請檢查您是否記得註冊您想讓您的收藏視圖在某個合理的地方作出迴應的拖拽類型,即viewDidLoad - 請參閱下面的代碼片段 - 當然,當首先生成拖動數據時,在粘貼板中正在設置相同的拖動類型!

collectionView.register(forDraggedTypes: [dragType])