【发布时间】:2014-02-14 15:55:12
【问题描述】:
我制作了一个带有自定义视图的 Mac 应用程序,该视图是拖放文件的目的地。我的视图已注册为目的地,并且我已经实现了拖动操作方法。当我从 XCode 构建和运行应用程序时一切正常,但是当我从 Finder 打开 .app 时,拖动文件不起作用,并且我在控制台中看到以下错误:
由于异常“NSInvalidArgumentException”而取消拖动 (原因'启动路径不可访问')在拖动过程中被提升 会话
有人知道这是什么意思或为什么会发生吗?以下是相关代码:
#import "DragDestinationView.h"
@implementation DragDestinationView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// register for dragging types
[self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
highlight = NO;
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
if ( highlight ) {
//highlight by overlaying a gray border
[[NSColor whiteColor] setFill];
NSRectFill(dirtyRect);
[self setWantsLayer:YES];
self.layer.masksToBounds = YES;
self.layer.borderWidth = 10.0f;
[self.layer setBorderColor:[[NSColor grayColor] CGColor]];
}
else {
[self.layer setBorderColor:[[NSColor clearColor] CGColor]];
}
}
#pragma mark - Destination Operations
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
NSPasteboard *pboard = [sender draggingPasteboard];
if ([[pboard types] containsObject:NSFilenamesPboardType]) {
// check if it's a bin
NSString* filePath = [[NSURL URLFromPasteboard: [sender draggingPasteboard]] absoluteString];
if ([[[filePath substringFromIndex:[filePath length] - 4] lowercaseString] isEqualToString:@".bin"]) {
// it's a bin
highlight = YES;
[self setNeedsDisplay:YES];
return NSDragOperationCopy;
}
}
return NSDragOperationNone;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender
{
//remove highlight of the drop zone
highlight=NO;
[self setNeedsDisplay: YES];
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
//finished with the drag so remove any highlighting
highlight=NO;
[self setNeedsDisplay: YES];
return YES;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
if ( [sender draggingSource] != self ) {
NSString* filePath = [[NSURL URLFromPasteboard: [sender draggingPasteboard]] absoluteString];
filePath = [filePath substringFromIndex:7];
filePath = [filePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"file path = %@",filePath);
// send notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"filePathString" object:filePath];
}
return YES;
}
@end
注意:draggingEntered: 方法返回 NSDragOperationCopy 因为我喜欢带有绿色圆圈的箭头光标,并且告诉用户他们可以在这里拖动文件。我实际上对删除的文件所做的只是获取它的路径位置。
【问题讨论】:
标签: macos cocoa drag-and-drop