Skip to content

Instantly share code, notes, and snippets.

@dneprDroid
Created May 10, 2018 21:31
Show Gist options
  • Save dneprDroid/d70ae323a8fdc686d6b0ba9b9f170f89 to your computer and use it in GitHub Desktop.
Save dneprDroid/d70ae323a8fdc686d6b0ba9b9f170f89 to your computer and use it in GitHub Desktop.
DragDropImageView for Mac OS.
//
// DragDropImageView.h
// TFVideo
//
// Created by user on 2/1/18.
// Copyright © 2018 AlexO. All rights reserved.
//
#import <AppKit/AppKit.h>
@protocol DragDropImageViewDelegate
- (void)didDragImage:(NSImage*)image;
@end
@interface DragDropImageView : NSImageView
@property(weak, nonatomic) id<DragDropImageViewDelegate> dragDelegate;
@end
// DragDropImageView.m
#import "DragDropImageView.h"
@interface DragDropImageView ()
@property(nonatomic, assign) BOOL isReceivingDrag;
@end
@implementation DragDropImageView
- (void)awakeFromNib {
[super awakeFromNib];
[self registerForDraggedTypes:@[NSFilenamesPboardType, NSStringPboardType, NSURLPboardType]];
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
if (self.isReceivingDrag) {
NSBezierPath *path = [NSBezierPath bezierPathWithRect:self.bounds];
path.lineWidth = 4;
[[NSColor blueColor] set];
[path stroke];
}
}
- (void)setIsReceivingDrag:(BOOL)isReceivingDrag {
_isReceivingDrag = isReceivingDrag;
self.needsDisplay = YES;
}
- (BOOL)shouldAllowDrag:(id<NSDraggingInfo>)info {
BOOL canAccept = NO;
NSPasteboard *p = [info draggingPasteboard];
if ([p canReadObjectForClasses:@[NSURL.class] options:@{NSPasteboardURLReadingContentsConformToTypesKey : [NSImage imageTypes]}]) {
canAccept = YES;
} else {
}
return canAccept;
}
- (void)draggingExited:(id<NSDraggingInfo>)sender {
self.isReceivingDrag = NO;
}
- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
BOOL allow = [self shouldAllowDrag:sender];
self.isReceivingDrag = allow;
return allow ? NSDragOperationCopy : NSDragOperationNone;
}
- (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender {
self.isReceivingDrag = NO;
NSPasteboard *p = [sender draggingPasteboard];
if (!p) return NO;
NSArray *urls = [p readObjectsForClasses:@[NSURL.class] options:@{NSPasteboardURLReadingContentsConformToTypesKey : [NSImage imageTypes]}];
if (urls && urls.count > 0 && [urls.firstObject isKindOfClass:NSURL.class]) {
NSImage *image = [[NSImage alloc]initWithContentsOfURL:urls.firstObject];
if (image) [self.dragDelegate didDragImage: image];
return YES;
}
NSImage *result = [[NSImage alloc]initWithPasteboard:p];
if (result) {
[self.dragDelegate didDragImage: result];
return YES;
}
return NO;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment