Skip to content

Instantly share code, notes, and snippets.

@sooop
Created May 22, 2013 02:29
Show Gist options
  • Save sooop/5624862 to your computer and use it in GitHub Desktop.
Save sooop/5624862 to your computer and use it in GitHub Desktop.
Image view which supports image drag and drop.
#import <Foundation/Foundation.h>
@interface XSDragImageView : NSImageView <NSDraggingSource, NSDraggingDestination>
{
BOOL isHighLighted; // 테두리 표시 여부를 나타내는 값
}
@end
@implementation XSDragImageView
#pragma mark - init and dealloc
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self) {
[self registerForDraggedTypes:@[NSPasteboardTypeTIFF, NSPasteboardTypePNG, NSFilenamesPboardType]];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if(self) {
[self registerForDraggedTypes:@[NSPasteboardTypeTIFF, NSPasteboardTypePNG, NSFilenamesPboardType]];
}
return self;
}
#pragma mark - Mouse Action
-(void)mouseDown:(NSEvent *)theEvent
{
NSDraggingItem *dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter:self.image];
[dragItem setDraggingFrame:self.bounds contents:self.image];
[self beginDraggingSessionWithItems:dragItem event:theEvent source:self];
}
#pragma mark - Source Operation
-(NSDragOperation)draggingSession:(NSDraggingSession *)session sourceOperationMaskForDraggingContext:(NSDraggingContext)context
{
return NSDragOperationCopy;
// switch(context) {
// case NSDraggingContextOutsideApplication:
// return NSDragOperationCopy;
// break;
// case NSDraggingContextWithinApplication:
// default:
// return NSDragOperationGeneric;
// break;
// }
}
#pragma mark - Destination Operation
-(NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
NSPasteboard *pboard = [sender draggingPasteboard];
NSString *availableType = [pboard availableTypeFromArray:[self registeredDraggedTypes]];
if(availableType) {
isHighLighted = YES;
[self setNeedDisplay:YES];
return NSDragOperationCopy;
}
return NSDragOperationNone;
}
-(NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
NSPasteboard *pboard = [sender draggingPasteboard];
if([NSImage canInitWithPasteboard:pboard]) {
NSImage *copiedImage = [[NSimage alloc] initWithPasteboard:pboard];
self.image = [copiedImage autorelease];
return YES;
}
return NO;
}
-(void)concludeDragOperation:(id <NSDraggingInfo>)sender
{
isHighLighted = NO;
[self setNeedDisplay:YES];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment