Drag and Drop text file on MacOS X application

Looking for this answer on the internet, I didn’t find a compiled solution for this issue. So I decided to make a simple tutorial how to build an app that act as a drag destination of a text file.

How does it works?

MacOS has a sofisticated drag-and-drop operation’s to use in your application or between applications. Using this capabilities your application could act as a Dragging Source, a Drag Destination or both.

Create our solution

1) create a new project “Cocoa Application” in Xcode named DragTest.

2) create a new file “objective-c class” named DragDropView.

To implement the drag-and-drop behavior you will need this methods:

- (NSDragOperation)draggingEntered:(id)sender

(Invoked when the dragged image enters destination bounds or frame)

- (BOOL)prepareForDragOperation:(id)sender

(Invoked when the image is released)

- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender

(Invoked after the released image has been removed from the screen)

- (void)concludeDragOperation:(id)sender

(Invoked when the dragging operation is complete)

Here the implementation:

#import "DragDropView.h"

@implementation DragDropView

- (id)initWithFrame:(NSRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
    }
    return self;
}

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
    highlight=YES;
    [self setNeedsDisplay: YES];
	return NSDragOperationGeneric;
}

- (void)draggingExited:(id <NSDraggingInfo>)sender{
    highlight=NO;
    [self setNeedsDisplay: YES];
}

- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender {
    highlight=NO;
    [self setNeedsDisplay: YES];
    return YES;
}

- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender {
    NSArray *draggedFilenames = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
    if ([[[draggedFilenames objectAtIndex:0] pathExtension] isEqual:@"txt"]){
        return YES;
    } else {
        return NO;
    }
}

- (void)concludeDragOperation:(id <NSDraggingInfo>)sender{
    NSArray *draggedFilenames = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
    NSString *textDataFile = [NSString stringWithContentsOfFile:[draggedFilenames objectAtIndex:0] encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@", textDataFile);
}

- (void)drawRect:(NSRect)rect{
    [super drawRect:rect];
    if ( highlight ) {
        [[NSColor grayColor] set];
        [NSBezierPath setDefaultLineWidth: 5];
        [NSBezierPath strokeRect: [self bounds]];
    }
}

@end

3) Now, select the MainMenu.xib.

4) Drop one CustomView into the Window.

5) in the “identity inspector” tab, in the “custom class” comboBox select the DragDropView.

it’s done !

0 Responses to “Drag and Drop text file on MacOS X application”


Comments are currently closed.



Premium Wordpress Plugin