Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Duke Leto

macrumors regular
Original poster
Mar 17, 2008
166
0
I have created some simple code that allows you to press a button and a circle (represented by an NSView subclass) appears indide of another "main" view. I am trying to incorporate drag functionality so that the user can move the circle around. However, methods found on the Internet and methods I have tried to create are choppy and unreliable. The sample code from Apple allowed you to drag a rectangle that was drawn inside of another view - so only one view was involved, and only the position of the drawn rectangle changed. This kind of algorithm could not be applied to my situation.

Thanks in advance for the help!
 
I have created some simple code that allows you to press a button and a circle (represented by an NSView subclass) appears indide of another "main" view. I am trying to incorporate drag functionality so that the user can move the circle around. However, methods found on the Internet and methods I have tried to create are choppy and unreliable. The sample code from Apple allowed you to drag a rectangle that was drawn inside of another view - so only one view was involved, and only the position of the drawn rectangle changed. This kind of algorithm could not be applied to my situation.

Thanks in advance for the help!

Not too sure, but if there is already an algorithm for changing the position of a square, and it works. Why not make it change the drawing position of your NSView? Provided you ARE drawing/positioning the view programatically and not in IB.
 
Not too sure, but if there is already an algorithm for changing the position of a square, and it works. Why not make it change the drawing position of your NSView? Provided you ARE drawing/positioning the view programatically and not in IB.

This. The frame member of an NSView gives you the NSRect corresponding to the position of the NSView inside its supeview. Change the x and y members to change the position of the NSView inside its superview.
 
I know how to use the frame property to move a rectangle!!!!!

It is *where* to move the rectangle that is the problem.
 
Finally!!!!!

Code:
// -------------------- MOUSE EVENTS ------------------- \\ 

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

- (void)mouseDown:(NSEvent *)theEvent
{
	lastDragLocation = [theEvent locationInWindow]; 
}

- (void)mouseDragged:(NSEvent *)theEvent
{
	NSPoint newDragLocation = [theEvent locationInWindow];
	NSPoint thisOrigin = [self frame].origin;
	thisOrigin.x += (-lastDragLocation.x + newDragLocation.x);
	thisOrigin.y += (-lastDragLocation.y + newDragLocation.y);
	[self setFrameOrigin:thisOrigin];
	lastDragLocation = newDragLocation;
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.