Mac 苹果拖拽文件导入实现
Mac 苹果拖拽文件导入实现
- drag drop import file
- 实现的功能
- 先上代码
drag drop import file
实现的功能
在导入文件到基于Mac开发的程序时,可以使用拖拽文件到程序界面的方式进行导入,这样的导入方式更加的直观,更加的符合人对事物的理解。
先上代码
先自定义一个View,这个View用来接收拖拽到上面的文件信息。
DragDropImageView.h
#import
@protocol DragDropViewDelegate;@interface DragDropImageView : NSImageView
@property (weak) id delegate;
@end@protocol DragDropViewDelegate
-(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)sender{NSPasteboard *pboard = [sender draggingPasteboard];if ([[pboard types] containsObject:NSPasteboardTypeFileURL]) {return NSDragOperationCopy;}return NSDragOperationNone;
}/***第三步:当在view中松开鼠标键时会触发以下函数***/
-(BOOL)prepareForDragOperation:(id)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
@interface ExampleViewController () //接受文件拖拽的view
@property (nonatomic, strong) DragDropImageView *drapDropImageView;@end@implementation ExampleViewController- (void)viewDidLoad {[super viewDidLoad];[self setupView];
}- (void)setupView {//设置接受拖动文件的view{//创建DragDropImageViewself.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 {//自己对文件的操作
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
