我正在尝试实现从 NSCollectionView中拖动条目(而不仅仅是把东西拖到它上)。
在我的示例代码中,我通过拖动注册CollectionView:
collectionView.registerForDraggedTypes([.URL])
collectionView.setDraggingSourceOperationMask(.every, forLocal: false)
collectionView.setDraggingSourceOperationMask(.every, forLocal: true)然后,我从NSCollectionViewDelegate协议实现了这些方法:
func collectionView(_ collectionView: NSCollectionView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool {
return true
}
func collectionView(_ collectionView: NSCollectionView, pasteboardWriterForItemAt indexPath: IndexPath) -> NSPasteboardWriting? {
return URL(fileURLWithPath: #file) as NSPasteboardWriting
}
func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItemsAt indexPaths: Set<IndexPath>) { }
func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, dragOperation operation: NSDragOperation) { }但他们两个都没有被称为!为什么不行?
如果我添加这两种方法:
func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndexPath proposedDropIndexPath: AutoreleasingUnsafeMutablePointer<NSIndexPath>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionView.DropOperation>) -> NSDragOperation {
return .move
}
func collectionView(_ collectionView: NSCollectionView, acceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
return true
}然后,我可以成功地将文件从桌面放到集合视图中,但仍然不能相反。
到底怎么回事?
向你问好,V。
发布于 2018-08-24 10:03:03
这里完全一样。
它看起来像一个bug (Xcode 9.4.1,Swit 4.1.2)。
正如您提到的,validateDrop和acceptDrop在我的应用程序中被调用。
但是(例如),endedAt没有:
func collectionView(_ collectionView: NSCollectionView,
draggingSession session: NSDraggingSession,
endedAt screenPoint: NSPoint,
dragOperation operation: NSDragOperation) { }我能找到的唯一解决办法(对于上面的endedAt委托)是子类NSCollectionView (在下面的示例中我称之为ImageCollectionView ),并实现自己的delegate/protocol
import Cocoa
protocol ImageCollectionViewDelegate {
func didExitDragging()
}
class ImageCollectionView: NSCollectionView {
var imageCollectionViewDelegate: ImageCollectionViewDelegate?
}
extension ImageCollectionView {
override func draggingExited(_ sender: NSDraggingInfo?) {
super.draggingExited(sender)
imageCollectionViewDelegate?.didExitDragging()
}
}(我不得不称它为imageCollectionViewDelegate,以避免与已经存在的delegate属性发生冲突。)
然后,在我的控制器(我称之为ImageCollectionViewController)中:
@IBOutlet internal weak var imageCollectionView: ImageCollectionView! {
didSet {
imageCollectionView.imageCollectionViewDelegate = self
}
}
extension ImageCollectionViewController: ImageCollectionViewDelegate {
func didExitDragging() {
highlightDestination(false)
}
}这使我可以做的东西,当拖动外的集合。
在这个非常简单的用例中,只需打开/关闭目标视图的突出显示:

理想情况下,所有这些额外的代码都是不必要的。
我也在寻找正确的方法来处理这件事。
https://stackoverflow.com/questions/51621499
复制相似问题