Mac os - 添加文件拖动 单文件、多文件支持

Mac os文件拖动支持,是在NSView层级别进行监听。

所以第一步写Window下的View实现。

直接贴代码


@protocol ReadFileViewDelegate 
///接收单个文件
- (void)receivedFileUrl:(NSURL *)fileUrl;
///接收到多个文件
- (void)receivedFileUrlList:(NSArray< NSURL *> *)fileUrls;
@end

@interface ReadFileView : NSView
@property (weak, nonatomic) IBOutlet id delegate;
@end
@implementation ReadFileView
//MARK: - life cycle
- (id)initWithFrame:(NSRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //注册文件拖动事件
        [self registerForDraggedTypes:[NSArray arrayWithObjects:NSPasteboardTypeFileURL, nil]];
    }
    
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    //注册文件拖动事件
    [self registerForDraggedTypes:[NSArray arrayWithObjects:NSPasteboardTypeFileURL, nil]];
}

- (void)dealloc {   
    [self unregisterDraggedTypes];
}

//MARK: - private methods
//当文件被拖动到界面触发
- (NSDragOperation)draggingEntered:(id )sender {
    NSPasteboard *pboard;
    NSDragOperation sourceDragMask;
    
    sourceDragMask = [sender draggingSourceOperationMask];
    pboard = [sender draggingPasteboard];
    if ( [[pboard types] containsObject:NSPasteboardTypeFileURL] ) {
        if (sourceDragMask & NSDragOperationLink) {
            return NSDragOperationLink;//拖动变成箭头
        } else if (sourceDragMask & NSDragOperationCopy) {
            return NSDragOperationCopy;//拖动会变成+号
        }
    }
    return NSDragOperationNone;
}

//当文件在界面中放手
-(BOOL)prepareForDragOperation:(id)sender{
    NSPasteboard *zPasteboard = [sender draggingPasteboard];
    // 判断是否是单文件
    if (zPasteboard.pasteboardItems.count <= 1) {
        NSURL *url = [NSURL URLFromPasteboard:zPasteboard];
        if (url && self.delegate) {
            [self.delegate receivedFileUrl:url];
        }
    } else {
        //多文件
        NSArray *list = [zPasteboard propertyListForType:NSFilenamesPboardType];
        NSMutableArray *urlList = [NSMutableArray array];
        for (NSString *str in list) {
            NSURL *url = [NSURL fileURLWithPath:str];
            [urlList addObject:url];
        }
        if (urlList.count && self.delegate) {
            [self.delegate receivedFileUrlList:urlList];
        }
    }
    return YES;
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    
    // Drawing code here.
}
@end

读取文件的绝对路劲需要转换成NSURL获取path即可。

NSURL *url = [NSURL URLFromPasteboard:zPasteboard];
NSLog(@"%@",[url path]);

文件读取的方法,可以使用NSFileManager读取文件和文件信息。

你可能感兴趣的:(Mac os - 添加文件拖动 单文件、多文件支持)