Collecting mouseclicks

This is a common challenge in drawing-related applications: the user clicks their mouse, and the application does something with those coordinates.
<Assumption> If you have already drawn an object, the code will be different, because now you have an object that knows its own coordinates and that should be able to tell when it’s clicked.</Assumption>

 

Context: NSView subclass

The action here takes place in an NSView, which needs to be inside an NSWindow. Cocoa offers NSView subclasses as one of its class templates.

Declaration in view.h

NSPoint points[4];
	/*array that can store four points*/
NSUInteger pointCount;
	/*unsigned since the number in an array
can never be negative*/

Function Logic

The user clicks the mouse; the application stores the clicks in the points array. When it has four points, it tells itself that it needs to redraw

[self setNeedsDisplay: YES];

which triggers whatever sits inside

- (void)drawRect:(NSRect)rect

Instead of doing that, the points could be stored or manipulated further.

Function

- (void)mouseDown: (NSEvent*)theEvent
{
	NSPoint click = [self convertPoint: [theEvent locationInWindow]
							 from View:nil]; /*from this view
rather than another one in the same window*/
	points[pointCount++ % 4] = click; /*keep going until you have four (see note below)*/
	if (pointCount % 4 ==0)//if you have four, do this
	{
		[self setNeedsDisplay: YES]; /* this triggers whatever
code sits in - (void)drawRect:(NSRect)rect */
	}
}

[copied from David Chisnall: Cocoa Programming Fundamentals]
For a closer explanation of points[pointCount++ % 4] = click see this post

Caveats

The % syntax is, as I ought to have known, the modulo operator.
I wasn’t able yet to verify that this actually runs, since I’ve had trouble linking the view to the Window following the example I was given (wrong version of Xcode, too much hassle right now.)

Linkage

(to be implemented)

Antidotes

none

Entanglements

  • click-and-drag
  • double-click
  • rightclick

Areas

  • User Input
  • Drawing
This entry was posted in Wiki and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>