TweetFollow Us on Twitter

What a Drag Volume Number: 16 (2000)
Issue Number: 12
Column Tag: Mac OS X

What a Drag!

By Andrew C. Stone

Creating drag wells in Cocoa

The richness of the user interface in Macintosh OS X is due, in part, to the abundance of elements that allow dragging and dropping of data within and between applications. For example, Cocoa uses drag and drop for applying color swatches to text selections and objects. Stone Design's flagship application, Create[TM], makes heavy use of the drag and drop metaphor. A library of resources allows users to drag in components, pages, effects, blends, images, and patterns. The user can quickly save a selection of graphics to one of many image formats with Create's "Image Well". This article will cover the basics of creating a custom control which allows a user to drag in a file, and then allows the user to drag out the file.

Create's image well lets you drag out data in various image formats.

First, a bit of article administrivia. Mac OS X has been a fast moving target with the various developer releases, Public Beta, and soon OS X GM (for Golden Master which always reminds me of that Eddy Murphy movie about G)! Because of the changes introduced with each release and the several month lag time between penning articles and when MacTech hits the stands, there are times when what I've written doesn't jive with the current reality. To address this, I've added a section to the Stone Design website for MacTech article updates and errata. So if you get confused, check out to see if there are updates, and if not, email me so I can post fixes.

It's actually quite simple to create new types of user interface controls using Cocoa because of the well designed hierarchy of classes that comprise the Application framework. Your first job is to find an existing class that your control can inherit from, which will reduce the amount of code that you have to write. I keep /Developer/Documentation/Cocoa/cocoa.html open so I can quickly navigate to the AppKit or Foundation API's. But an even easier way to look at the object hierarchy is to use InterfaceBuilder. First launch ProjectBuilder and create a new Cocoa Application project named ImageWellTester. Click on the "Resources" triangle in the Files and Groups outline view, and double-click the MainMenu.nib. This will launch InterfaceBuilder.

Click on the "Classes" tab of the document window, and then explore the NSObject outline view:

Interface Builder lets you explore the hierarchy of objects offered by Cocoa.

Our drag well is definitely a subclass of NSView, but we can gain further functionality by subclassing NSControl, which gives us the target/action support. Select NSControl in the Classes pane. If you hold down the CONTROL key while clicking on NSControl, a context-sensitive menu appears. Do this and select "Subclass". A new class which inherits from NSControl is created and named, by default, MyControl. Rename the class to DragWell.

Why write code if you can have it written for you? You can use InterfaceBuilder to produce stub files where all you have to do is fill in the functionality in the stubbed out methods. Click on the "outlet" icon to add instance variables to the class, and the "+" icon to add actions to the class. For now, we don't have any to add. Be sure DragWell is selected, and choose select "Create Files..." from the Classes menu (or again using the context menu via CONTROL key). They will be named DragWell.m and DragWell.h - leave the "Insert into Project Builder" selected and click OK.

Drag out a "Custom View" from the IB palette window, second tab, onto to the main window. Choose Tools->Inspector->Custom Class popup button, and click on "DragWell". The custom view should now say "DragWell". Save the file.

Go back to ProjectBuilder, select the newly added DragWell.h and DragWell.m and you'll see the stub:

#import <Cocoa/Cocoa.h>

@interface DragWell : NSControl

#import "DragWell.h"

@implementation DragWell


Every custom view must define its own drawing method, drawRect:, where the actual drawing of the view takes place. We'll want a simple, depressed bezeled look, with an icon to drag in the center. And our control will adhere to two protocols - NSDraggingDestination and NSDraggingSource, to allow both dragging out of info and accepting dragged in info. A complete list of the methods required by the protocols are found in:


Here's the 'well' commented code for the DragWell - type it in (or download it from You can copy and paste it as a template for use in other objects, modifying where needed to copy other data types to the drag pasteboard as needed.

+++++++++++ DragWell.h ++++++++++++++++

#import <Cocoa/Cocoa.h>

@interface DragWell : NSControl
    NSImage *image;      // the image displayed and dragged by the user
    NSString *file;      // the file path that the user will drag out
    unsigned int last;   // for optimizing the draggingUpdated: method

// if you want to programmatically set a file in the well:
- (void)setFile:(NSString *)newFile;


+++++++++++ DragWell.m ++++++++++++++++

#import "DragWell.h"

/* Example source by Andrew Stone for MacTech */

@implementation DragWell

// when our DragWell is reconstituted from the nib file, awakeFromNib gets called

- (void) awakeFromNib
     // this is where you register for various types of drag pasteboards:
     [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];

// Never add an ivar which allocates memory without releasing it in dealloc:
// Don't Litter!

- (void)dealloc {
    [file release];
    [image release];
    [super dealloc];

// Every custom view must implement drawRect:
// We'll draw our depressed bezeled rect
// and if there is a file, we'll draw an image for dragging out

- (void)drawRect:(NSRect)rects
    // one simple call draws the depressed bezel:
    NSDrawGrayBezel([self bounds] , [self bounds]);

    // if you like the pinstripes, then include these two lines:
    [[NSColor windowBackgroundColor] set];
    NSRectFill(NSInsetRect([self bounds],3.0,3.0));

    // find the center of the view and draw the image over:
    if (image != nil) {
        NSPoint p;
        NSSize sz = [image size];
        p.x = ([self bounds].size.width - sz.width)/2.;
        p.y = ([self bounds].size.height - sz.height)/2.;
        [image compositeToPoint:p operation:NSCompositeSourceOver];

// When we set the file, we also set the image which we get from the NSWorkspace:

- (void)setFile:(NSString *)newFile {

    // it's good practice to not do any work if nothing would change:
    if (![newFile isEqualToString:file]) {
        // live clean and let your works be seen:
        [file release];
        [image release];
        // copy the newFile into our instance variable file:
        file = [newFile copyWithZone:[self zone]];
        // check if the file is nil or empty string:
        if (!file || [file isEqualToString:@""]) {
            image = nil;
        } else {
            // we have a file, now let's find the image for that file:
            image = [[[NSWorkspace sharedWorkspace] iconForFile:file]retain];
        // we'll need to redraw next event 
        // this is the approved Cocoa way of setting ourselves "dirty"
        [self setNeedsDisplayInRect:[self bounds]];

// here we copy the filename to the pasteboard
// I like to factor this out because it may vary from object to object:

- (BOOL)copyDataTo:pboard
    if (file != nil && ![file isEqualToString:@""]) {
        [pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:self];
        [pboard setPropertyList:[NSArray arrayWithObject:file] forType:NSFilenamesPboardType];
        return YES;
    } else return NO;

// To add drag away functionality to a control, implement these:

// draggingSourceOperationMaskForLocal lets you control the behavior of what should
// happen with the data on the pasteboard: copy, link or any
// the isLocal flag tells you whether the object querying is from within your app
// or from another application running on the system

- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)isLocal
        if (isLocal) return NSDragOperationCopy;
        return NSDragOperationCopy|NSDragOperationGeneric|NSDragOperationLink;

// The simple dragImage:at:offset:event:pasteboard:source:slideback: method
// is all we do to initiate and run the actual drag sequence
// But we only do this if we have an image and we successfully write our data
// to the pasteboard in copyDataTo: method

- (void)mouseDown:(NSEvent *)e
        NSPoint location;
        NSSize size;
        NSPasteboard *pb = [NSPasteboard pasteboardWithName:(NSString *) NSDragPboard];

        if (image && [self copyDataTo:pb]) {
                size = [image size];
    location.x = ([self bounds].size.width - size.width)/2;
    location.y = ([self bounds].size.height - size.height)/2;

                [self dragImage:image at:location offset:NSZeroSize event:(NSEvent *)e
pasteboard:pb source:self slideBack:YES];

// To add drag acceptance functionality to a control, implement these methods:

// this is called when the drag enters our view
// by returning NSDragOperationCopy
- (unsigned int) draggingEntered:sender
    NSPasteboard   *pboard;

     last      = NSDragOperationNone;
     pboard    = [sender draggingPasteboard];

// we don't acept drags if we are the provider!!
     if ([sender draggingSource] == self) return NSDragOperationNone;

     if ([[pboard types] containsObject:NSFilenamesPboardType]) {
         if (image == nil) {
            image = [[[NSWorkspace sharedWorkspace] iconForFile:[[pboard
             [self setNeedsDisplayInRect:[self bounds]];
   // we'll copy or link depending on the intent of the dragging source:
   last = [sender draggingSourceOperationMask]; 
     return last;

// instead of constantly rechecking the pasteboard as the mouse moves inside the view
// we'll simply return the cached value that we set in 'last' in draggingEntered:

- (unsigned int) draggingUpdated:sender
     return last;

// Because we're providing feedback by setting the file right when the user enters
// we'll need to undo that work if the user does not let go of the drag inside and exits instead:

- (void) draggingExited:sender
    // the user has exited -> clean up:     
    if ([sender draggingSource] != self)  {
        if (file == nil) {
            // then unset the file image we set in mouseEntered as feedback...
            [image release];
            image = nil;
            [self setNeedsDisplayInRect:[self bounds]];
        last = NSDragOperationNone;

// any dragging clean up might be done here
// don't forget to return YES!

- (BOOL) prepareForDragOperation:sender
     return YES;

// Actually do the work in this method if it's not too time consuming
// Otherwise, you may consider returning YES, and doing the work
// in concludeDragOperation to prevent the drag from sliding back
// because it "timed out"

- (BOOL) performDragOperation:(id <NSDraggingInfo>)sender
    NSPasteboard   *pboard;
    pboard    = [sender draggingPasteboard];
    [self setFile:[[pboard propertyListForType:NSFilenamesPboardType]objectAtIndex:0]];
    return YES;

- (void)concludeDragOperation:(id <NSDraggingInfo>)sender
    // we already did the work in draggingEntered
    // You might notify some other object that the file is here

// this is good if you want to be able to drag out data even if the window is not
// front most, the first click will do more than just bring the window to front -
// It will also allow the drag to begin on that first mouse down

- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent {
    return YES;



Adding drag and drop support to controls and views is very easy in Cocoa. Because ease of use and intuitive behavior is the keystone of Mac OS X, be sure to make your applications conform to this model.

Andrew Stone <> washes windows at Stone Design Corp <> and divides his time between writing applications for Mac OS X and raising farm animals, including children.


Community Search:
MacTech Search:

Software Updates via MacUpdate

AirPort Utility 6.3.6 - Set up and manag...
Note: Most recent release available only within OS X 10.11 El Capitan update. Use AirPort Utility to set up and manage your Wi-Fi network and AirPort base stations, including AirPort Express, AirPort... Read more
Quicksilver 1.3.1 - Application launcher...
Quicksilver is a light, fast and free Mac application that gives you the power to control your Mac with keystrokes alone. Quicksilver allows you to find what you need quickly and easily, then act... Read more
Tidy Up (Five Users) 4.1.5 - Find duplic...
Tidy Up is a complete duplicate finder and disk-tidiness utility. With Tidy Up you can search for duplicate files and packages by the owner application, content, type, creator, extension, time... Read more
Mellel 3.4.3 - The word processor of cho...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
Skype - Voice-over-internet p...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
Bookends 12.6.0 - Reference management a...
Bookends is a full-featured bibliography/reference and information-management system for students and professionals. Access the power of Bookends directly from Mellel, Nisus Writer Pro, or MS Word (... Read more
Apple iBooks Author 2.4 - Create and pub...
Apple iBooks Author helps you create and publish amazing Multi-Touch books for iPad. Now anyone can create stunning iBooks textbooks, cookbooks, history books, picture books, and more for iPad. All... Read more
Web Snapper 3.3.9 - Capture entire Web p...
Web Snapper lets you capture Web pages exactly as they appear in your browser. You can send them to a file as images or vector-based, multi-page PDFs. It captures the whole Web page - eliminating the... Read more
Tunnelblick 3.6beta10 - GUI for OpenVPN...
Tunnelblick is a free, open source graphic user interface for OpenVPN on OS X. It provides easy control of OpenVPN client and/or server connections. It comes as a ready-to-use application with all... Read more
EtreCheck 2.5.1 - For troubleshooting yo...
EtreCheck is a simple little app to display the important details of your system configuration and allow you to copy that information to the Clipboard. It is meant to be used with Apple Support... Read more

Camel Up (Games)
Camel Up 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: | Read more »
The Martian: Bring Him Home (Games)
The Martian: Bring Him Home 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Based on the best selling novel and critically acclaimed film, THE MARTIAN tells the story of Astronaut Mark... | Read more »
This Week at 148Apps: September 21-30, 2...
Leap Into Fall With 148Apps How do you know what apps are worth your time and money? Just look to the review team at 148Apps. We sort through the chaos and find the apps you're looking for. The ones we love become Editor’s Choice, standing out above... | Read more »
Tweetbot 4 for Twitter (Social Networki...
Tweetbot 4 for Twitter 4.0 Device: iOS Universal Category: Social Networking Price: $4.99, Version: 4.0 (iTunes) Description: *** 50% off for a limited time. *** | Read more »
Mori (Games)
Mori 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Stop, rewind and unwind with Mori. Time is always running, take a moment to take control. Mori is an action puzzle game about infinitely... | Read more »
100 Years' War (Games)
100 Years' War 1.0 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0 (iTunes) Description: | Read more »
Tower in the Sky (Games)
Tower in the Sky 0.0.60 Device: iOS Universal Category: Games Price: $1.99, Version: 0.0.60 (iTunes) Description: | Read more »
hocus. (Games)
hocus. 1.0.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0.0 (iTunes) Description: New, polished, mind-bending, minimal puzzle game with dozens of levels and extra-ordinary design Features:- Beautifully crafted... | Read more »
Mos Speedrun 2 (Games)
Mos Speedrun 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Mos is back, in her biggest and most exciting adventure ever! Wall-jump to victory through 30 mysterious, action packed levels... | Read more »
3D Touch could be a game-changer, but it...
Were you one of the lucky/financially secure enough ones to buy a new iPhone 6s or iPhone 6s Plus over the weekend? Yup, me too (I’m not convinced I was either of those two things, but let’s go with lucky for now), so I thought I’d delve into just... | Read more »

Price Scanner via

Apple refurbished iPad Air 2s available for u...
Apple has Certified Refurbished iPad Air 2s available for up to $140 off the price of new models. Apple’s one-year warranty is included with each model, and shipping is free: - 128GB Wi-Fi iPad Air 2... Read more
Save up to $100 on Mac AppleCare Protection P...
Adorama has 3-Year AppleCare Warranties on sale for up to $100 off MSRP including free shipping plus NY & NJ sales tax only: - Mac Laptops 15″ and Above: $249 $100 off MSRP - Mac Laptops 13″ and... Read more
Updated Mac Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
12-inch MacBooks in stock for up to $120 off,...
Adorama has 12″ Retina MacBooks in stock for up to $120 off MSRP including free shipping plus NY & NJ sales tax only. For a limited time, Adorama will include a free Apple USB-C to USB Adapter,... Read more
15-inch 2.2GHz Retina MacBook Pro on sale for... has the 15″ 2.2GHz Retina MacBook Pro on sale for $1799 including free shipping. Their price is $200 off MSRP, and it’s the lowest price available for this model (except for Apple’s $1699... Read more
iPhone 6s and 6s Plus Feature Improved Durabi...
Upgraded components in the new iPhone 6s Plus cost $16 more than the components in the earlier iPhone 6 Plus according to a preliminary estimate from IHS Inc. The bill of materials (BOM) for an... Read more
13-inch Retina MacBook Pros on sale for up to...
Adorama has 13″ Retina MacBook Pros on sale for up to $130 off MSRP. Shipping is free, and Adorama charges sales tax for NY & NJ residents only: - 13″ 2.7GHz/128GB Retina MacBook Pro: $1199.99 $... Read more
Apple refurbished 2014 13-inch Retina MacBook...
Apple has Certified Refurbished 2014 13″ 2.6GHz/128GB SSD Retina MacBook Pros available $979, $320 off original MSRP. An Apple one-year warranty is included, and shipping is free: - 13″ 2.6GHz/128GB... Read more
iOS 9 Reflections Ten Days In – The ‘Book Mys...
I’ve never been much of an early adopter by philosophy or temperament, although I did buy the iPad Air 2 I’m typing this column on last fall only about a month after Apple unveiled it. However, my... Read more
Apple refurbished Time Capsules available for...
Apple has certified refurbished Time Capsules available for $120 off MSRP. Apple’s one-year warranty is included with each Time Capsule, and shipping is free: - 2TB Time Capsule: $179, $120 off - 3TB... Read more

Jobs Board

Senior Payments Security Manager - *Apple*...
**Job Summary** Apple , Inc. is looking for a highly motivated, innovative and hands-on senior payments security manager to join the Apple Pay security team. You will Read more
*Apple* Solutions Consultant - Retail Sales...
**Job Summary** As an Apple Solutions Consultant (ASC) you are the link between our customers and our products. Your role is to drive the Apple business in a retail Read more
*Apple* Site Security Manager - Apple (Unite...
**Job Summary** The Site Security Manager is a high-profile security position at Apple . The Site Manager is the face of Apple Global Security (GS) and primary point Read more
*Apple* Fulfillment Operations Execution Ana...
**Job Summary** The AMR Apple Fulfillment Operations Team is seeking a talented team player to drive the Apple Online Store (AOS) fulfillment performance to ensure a Read more
*Apple* Distinguished Educator (ADE) Communi...
**Job Summary** Apple is seeking candidates for a new position on the Apple Distinguished Educator (ADE) Program team as ADE Community Support Manager. Join a team Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.