Created
October 17, 2016 11:07
-
-
Save PaulChana/2f1c11d495d79b250c36805851e6ac0a to your computer and use it in GitHub Desktop.
NSTextField enabled for drag and drop from finder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Cocoa/Cocoa.h> | |
@interface DragAndDropTextField : NSTextField | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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