I've never dealt much with NSViews so I am at a loss on this. I have a custom class that contains an NSImage
ivar. I also have a subclass of NSView
that contains an array of instances of my custom class. The NSImage
from the custom class gets drawn at the center of the NSView
upon creation. I need to be able to drag that NSImage
around the NSView
freely.
I have implemented the following methods to get started:
-(void)mouseDown:(NSEvent *)theEvent
{
[self beginDraggingSessionWithItems: /* I don't know what to put here */
event:theEvent
source:self];
}
I have tried placing the NSImage
object from my custom class in an array as the item to drag but an exception is raised. I also tried creating an NSDraggingItem
to place in there but it could not write the object to the pasteboard and raised an exception.
-(void)draggingSession:(NSDraggingSession *)session willBeginAtPoint:(NSPoint)screenPoint
{
NSLog(@"began");
}
-(void)draggingSession:(NSDraggingSession *)session movedToPoint:(NSPoint)screenPoint
{
NSLog(@"moved");
}
-(void)draggingSession:(NSDraggingSession *)session endedAtPoint:(NSPoint)screenPoint operation:(NSDragOperation)operation
{
NSLog(@"ended");
}
These methods get called properly as I click and drag my mouse around my subclass of NSView
however they are useless until I can get the object to move.
I believe the answer may be to create an NSDraggingItem
for each image and use that to move them freely around the view however I could not get it to work with even one object and do not know how to properly implement this idea. Any help is appreciated.
Went through a lot of headache on this one but finally figured it out. Instead of using beginDraggingSessionWithItems:event:source
I used dragImage:at:offset:event:pasteboard:source:slideBack:
. I keep track of the coordinates of each image in the view and can tell whether a specific image was clicked on or not by utilizing the following method I wrote in mouseDown:
-(BOOL)clickedAtPoint:(NSPoint)point InsideRect:(NSRect)rect
{
if ((point.x < (rect.origin.x + rect.size.width) &&
point.y < (rect.origin.y + rect.size.height)) &&
point.x > rect.origin.x && point.y > rect.origin.y) {
return YES;
}
return NO;
}