PDA

View Full Version : Using key strokes




richifie
Jun 10, 2012, 11:04 AM
How do i use key strokes to set off an action. Like on a game, pressing the left arrow key makes an imageView move two pixels to the left... or something.

So how do i do this?

Would it be in an "if" function, or would the keystroke set off an IBAction?

Thank you in advance,

-David, the MASSIVE noob.



gnasher729
Jun 10, 2012, 01:28 PM
How do i use key strokes to set off an action. Like on a game, pressing the left arrow key makes an imageView move two pixels to the left... or something.

So how do i do this?

Would it be in an "if" function, or would the keystroke set off an IBAction?

Thank you in advance,

-David, the MASSIVE noob.

Neither.

NSView is a subclass of NSResponder. Read the documentation for NSResponder, then in your view, you override the NSResponder methods that you want to override.

For example add this method to your view and see what happens:

- (void)keyDown:(NSEvent *)theEvent
{
NSLog (@"keyDown event %@", theEvent);
[super keyDown:theEvent];
}

richifie
Jun 10, 2012, 01:53 PM
Neither.

NSView is a subclass of NSResponder. Read the documentation for NSResponder, then in your view, you override the NSResponder methods that you want to override.

For example add this method to your view and see what happens:

- (void)keyDown:(NSEvent *)theEvent
{
NSLog (@"keyDown event %@", theEvent);
[super keyDown:theEvent];
}


Okay, so thank you very much for the help, and it helps a lot. Through reading the class reference i get that that code prints to the log the key that was pressed, by how would i perform an action when a specific key is pressed, for example: the "D" key.

Thank you in advance,

-David, the MASSIVE noob.

larswik
Jun 10, 2012, 02:27 PM
Are you learning how to program by trying to solve a specific problem, or are you learning using a book in a structured way?

If you are finishing for specific answers to solve your problem you more then likely will get something to work at some point but no idea why it works. Start at the beginning.

I started here "Learn C on the Mac".

chown33
Jun 10, 2012, 02:34 PM
Okay, so thank you very much for the help, and it helps a lot. Through reading the class reference i get that that code prints to the log the key that was pressed, by how would i perform an action when a specific key is pressed, for example: the "D" key.

The usual way: with if or switch statements, evaluating the value of NSEvent's keyCode method.