NSView Dragging

Discussion in 'Mac Programming' started by Duke Leto, Jun 22, 2009.

  1. macrumors regular

    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!
  2. macrumors 68030


    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.
  3. macrumors 68000


    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.
  4. macrumors regular

    I know how to use the frame property to move a rectangle!!!!!

    It is *where* to move the rectangle that is the problem.
  5. macrumors regular


    // -------------------- 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;

Share This Page