Note that there are some explanatory texts on larger screens.

plurals
  1. POCocoa: Accepting and responding to keystrokes
    text
    copied!<p>Hey everyone, I'm a newbie and I have what I anticipate will be a pretty easy question to answer. In order to learn a bit about event handling and drawing, I'm attempting to write a program that draws a black rectangle that increases in length every time the user hits the 'c' key. So far it just draws a black rectangle on a blue background without responding to keystrokes. Here is what I have so far:</p> <p>Input.h</p> <pre><code>#import &lt;Cocoa/Cocoa.h&gt; @interface Input : NSView { int length; } - (void)keyDown:(NSEvent *)theEvent; @end </code></pre> <p>Input.m</p> <pre><code>#import "Input.h" @implementation Input - (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; length = 10; if (self) { // Initialization code here. } return self; } - (void)drawRect:(NSRect)dirtyRect { //set variables NSRect r1; NSBezierPath *bp; // set background color [[NSColor blueColor] set]; NSRectFill(dirtyRect); //set color to black &amp; draw r1 [[NSColor blackColor] set]; r1 = NSMakeRect(1, 1, length, 10); bp = [NSBezierPath bezierPathWithRect:r1]; [bp fill]; } - (void)keyDown:(NSEvent *)theEvent { NSString *key = [theEvent characters]; if ( [key isEqualToString:@"c"] ) { length += 10; } } @end </code></pre> <p>I copied the keyDown method from Cocoa in a Nutshell, by the way. Needless to say, I don't really understand it. Do I have to make connections in IB in order to get the program to recognize keystrokes? Basically, I would love it if somebody could help me to get this program to work, because as of yet I have not gotten anything to respond to keystrokes.</p> <p>And here's <a href="http://proquest.safaribooksonline.com/0-596-00462-1/cocoaian-CHP-3-SECT-9" rel="nofollow noreferrer">Cocoa in a Nutshell</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload