I am following the 23th chapter of Aaron’s Cocoa programming for Mac OS X.
I have to drag a letter from a view and copy it in another application like text edit.
This is the portion of code with which I find problems:
- (void) mouseDragged:(NSEvent *)theEvent
{
NSPasteboard* pb=[NSPasteboard pasteboardWithName: NSDragPboard];
NSPoint down=[mouseDownEvent locationInWindow];
NSPoint drag=[theEvent locationInWindow],p;
NSSize size=[string sizeWithAttributes: attributes];
NSRect imageBounds;
NSImage* image=[NSImage alloc];
float distance;
distance= hypot(down.x-drag.x, down.y-drag.y);
if(distance<3 || [string length]==0)
return;
image=[image initWithSize: size];
imageBounds.origin=NSZeroPoint;
imageBounds.size=size;
[image lockFocus];
[self drawStringCenteredIn: imageBounds];
[image unlockFocus];
p=[self convertPoint: down fromView: nil];
p.x= p.x - size.width/2;
p.y= p.y - size.height/2;
[self writeToPasteboard: pb];
[self dragImage: image at: p offset: NSZeroSize event: mouseDownEvent pasteboard: pb source: self slideBack: YES];
}
Where:
– mouseDownEvent is an event previously saved, when the user has clicked on the lecter (mouseDown event);
– string is a NSMutableAttributesString, a string of max 1 lected that contains the lecter to be displayed into the view;
When the event occurs there is already a letter displayed on the view (so the string has length 1).If I forgot some important informations please ask.
The problem: the drag and drop operation works fine, but the problem is that while I drag the image, I don’t see the image displacing from it’s original position.
This is what I see while I drag the letter:
This is what I should see instead:

So the letter should displace, but this doesn’t happen.I don’t recognize the cause of this problem, I think that the method drawImageCenteredIn should work fine.That’s the code of this method:
- (void) drawStringCenteredIn: (NSRect) rect
{
NSSize size=[string sizeWithAttributes: attributes];
NSPoint origin;
origin.x= rect.origin.x+ (rect.size.width+size.width)/2;
origin.y=rect.origin.y + (rect.size.height+size.height)/2;
[string drawAtPoint: origin withAttributes: attributes];
}
It’s simple. The sign is incorrect in these two lines:
Here is the corrected method: