Skip to content

Instantly share code, notes, and snippets.

@PaulChana
Created October 17, 2016 11:07
Show Gist options
  • Save PaulChana/2f1c11d495d79b250c36805851e6ac0a to your computer and use it in GitHub Desktop.
Save PaulChana/2f1c11d495d79b250c36805851e6ac0a to your computer and use it in GitHub Desktop.
NSTextField enabled for drag and drop from finder
#import <Cocoa/Cocoa.h>
@interface DragAndDropTextField : NSTextField
@end
#import "DragAndDropTextField.h"
@interface DragAndDropTextField ()
@property (nonatomic) bool dragIsOver;
@end
@implementation DragAndDropTextField
- (void) awakeFromNib {
[self registerForDraggedTypes:[NSArray arrayWithObjects: NSFilenamesPboardType, nil]];
}
- (void)drawRect:(NSRect)dirtyRect {
[NSGraphicsContext saveGraphicsState];
[super drawRect:dirtyRect];
if (_dragIsOver)
{
[[[NSColor keyboardFocusIndicatorColor] colorWithAlphaComponent:0.25] set];
NSRectFill(NSInsetRect(self.bounds, 1, 1));
}
[NSGraphicsContext restoreGraphicsState];
}
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
if ( [[[sender draggingPasteboard] types] containsObject:NSFilenamesPboardType] ) {
_dragIsOver = true;
[self setNeedsDisplay];
return NSDragOperationCopy;
}
return NSDragOperationNone;
}
- (void)draggingExited:(nullable id <NSDraggingInfo>)sender {
_dragIsOver = false;
[self setNeedsDisplay];
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
NSPasteboard *pboard = [sender draggingPasteboard];
if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
NSString *url = [files objectAtIndex:0];
if (url)
{
self.stringValue = url;
_dragIsOver = false;
[self setNeedsDisplay];
}
}
return YES;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment