macos 文件拖入窗口

看到很多Mac上的工具类应用都可以直接拖入图片 或者 拖入文件直接使用,今天就来说一下文件拖入的使用方法

首先 新建一个文件继承NSView;
声明一个BOOL值

@property(nonatomic,assign)BOOL isDragIn;
- (void)drawRect:(NSRect)dirtyRect {

       [superdrawRect:dirtyRect];

       [self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType,nil]];

       if(_isDragIn) {

       NSLog(@"拖拽了");

    }
}
- (NSDragOperation)draggingEntered:(id)sender
{
_isDragIn=YES;

[self setNeedsDisplay:YES];

return NSDragOperationCopy;

}
- (void)draggingExited:(id)sender{

_isDragIn=NO;

[self setNeedsDisplay:YES];

}
- (BOOL)prepareForDragOperation:(id)sender{

_isDragIn=NO;

[self setNeedsDisplay:YES];

returnYES;

}
- (BOOL)performDragOperation:(id)sender{

if([senderdraggingSource] !=self)

{

NSArray* filePaths = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];

NSLog(@"文件地址%@",filePaths);

}

return YES;
}