Mac 苹果拖拽文件读取实现
drag drop import file
实现的功能
在导入文件到基于Mac开发的程序时,可以使用拖拽文件到程序界面的方式进行导入,这样的导入方式更加的直观,更加的符合人对事物的理解。
先上代码
先自定义一个View,这个View用来接收拖拽到上面的文件信息。
DragDropImageView.h
#import <Cocoa/Cocoa.h>
@protocol DragDropViewDelegate;
@interface DragDropImageView : NSImageView
@property (weak) id<DragDropViewDelegate> delegate;
@end
@protocol DragDropViewDelegate <NSObject>
-(void)dragDropViewFileDidReceiveList:(NSArray*)fileList;
@end
DragDropImageView.m
#import "DragDropImageView.h"
@implementation DragDropImageView
@synthesize delegate = _delegate;
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
}
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//NSPasteboardTypeFileURL这个根据需求进行修改
[self registerForDraggedTypes:[NSArray arrayWithObjects:NSPasteboardTypeFileURL, nil]];
}
return self;
}
/***
第二步:当拖动数据进入view时会触发这个函数,返回值不同会显示不同的图标
***/
-(NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender{
NSPasteboard *pboard = [sender draggingPasteboard];
if ([[pboard types] containsObject:NSPasteboardTypeFileURL]) {
return NSDragOperationCopy;
}
return NSDragOperationNone;
}
/***
第三步:当在view中松开鼠标键时会触发以下函数
***/
-(BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender{
// 获取拖动数据中的粘贴板
NSPasteboard *pboard = [sender draggingPasteboard];
NSString *fileURL;
NSArray *filelist;
// 判断是否拖进单文件
if (pboard.pasteboardItems.count <= 1) {
//直接获取文件路径
fileURL = [[NSURL URLFromPasteboard:pboard] path];
filelist = [NSArray arrayWithObjects:fileURL,nil];
}
//多文件,目前暂不支持
else {
filelist = [pboard propertyListForType:NSPasteboardTypeFileURL];
}
// 将接受到的文件链接数组通过代理传送
if(self.delegate && [self.delegate respondsToSelector:@selector(dragDropViewFileDidReceiveList:)])
[self.delegate dragDropViewFileDidReceiveList:filelist];
return YES;
}
@end
然后在需要的ViewController中添加以下代码
ExampleViewController.m
#import <Cocoa/Cocoa.h>
@interface ExampleViewController () <DragDropViewDelegate>
//接受文件拖拽的view
@property (nonatomic, strong) DragDropImageView *drapDropImageView;
@end
@implementation ExampleViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupView];
}
- (void)setupView {
//设置接受拖动文件的view
{
//创建DragDropImageView
self.drapDropImageView = [[DragDropImageView alloc] init];
self.drapDropImageView.layer.backgroundColor = [NSColor orangeColor].CGColor;
//设置代理
self.drapDropImageView.delegate = self;
//将创建的View添加到当前的View中
[self.view addSubview:self.drapDropImageView];
//设置DragDropImageView在当前View中的位置
[self.drapDropImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.equalTo(self.view);
make.trailing.equalTo(self.view);
make.top.equalTo(self.view);
make.bottom.equalTo(self.view);
}];
}
}
@end
#pragma mark DragDropImageViewDelegate
- (void)dragDropViewFileDidReceiveList:(NSArray *)fileList {
//判断是否为空
if(!fileList || [fileList count] <= 0)
return;
//暂时只支持单个文件
[self processImportFile:fileList[0]];
}
//文件操作详细内容
- (void)processImportFile:(NSString *)fileUrl {
//自己对文件的操作
}
网友评论