Finder 中的拖动始终是文件拖动,而不是图像拖动。您需要支持从 Finder 中拖动 URL。
为此,您需要声明您需要 URL 类型:
[[self sourcesTableView] registerForDraggedTypes:[NSArray arrayWithObject:(NSString*)kUTTypeFileURL]];
您可以像这样验证文件:
- (NSDragOperation)tableView:(NSTableView *)aTableView validateDrop:(id < NSDraggingInfo >)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)operation
{
//get the file URLs from the pasteboard
NSPasteboard* pb = info.draggingPasteboard;
//list the file type UTIs we want to accept
NSArray* acceptedTypes = [NSArray arrayWithObject:(NSString*)kUTTypeImage];
NSArray* urls = [pb readObjectsForClasses:[NSArray arrayWithObject:[NSURL class]]
options:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES],NSPasteboardURLReadingFileURLsOnlyKey,
acceptedTypes, NSPasteboardURLReadingContentsConformToTypesKey,
nil]];
//only allow drag if there is exactly one file
if(urls.count != 1)
return NSDragOperationNone;
return NSDragOperationCopy;
}
然后,您需要在调用该方法时再次提取 URL tableView:acceptDrop:row:dropOperation:
,从 URL 创建图像,然后对该图像执行某些操作。
Even though you are using Cocoa bindings, you still need to assign and implement an object as the datasource
of your NSTableView
if you want to use the dragging methods. Subclassing NSTableView
will do no good because the datasource methods are not implemented in NSTableView
.
You only need to implement the dragging-related methods in your datasource object, not the ones that provide table data as you're using bindings to do that. It's your responsibility to notify the array controller of the result of the drop, either by calling one of the NSArrayController
methods such as insertObject:atArrangedObjectIndex:
or by modifying the backing array using Key-Value Coding-compliant accessor methods.