Connor
Connor

Reputation: 4168

Detect Enter/Tab/Up/Down keys in NSTextView?

Cocoa noob here. I'm wondering how I can capture the Enter and tab keys onKeyDown whilst the user is typing in an NSTextView?

Thanks!

Upvotes: 6

Views: 1280

Answers (2)

Steve Shepard
Steve Shepard

Reputation: 221

The easiest way is to implement the - (BOOL)textView:(NSTextView *)aTextView doCommandBySelector:(SEL)aSelector delegate method and look for the insertNewline: and insertTab: selectors.

- (BOOL)textView:(NSTextView *)aTextView doCommandBySelector:(SEL)aSelector
{
    if (aSelector == @selector(insertNewline:)) {
        // Handle the Enter key
        return YES;
    } else if (aSelector == @selector(insertTab:)) {
        // Handle the Tab key
        return YES;
    }

    return NO;

}

Upvotes: 4

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

You should handle keyDown:(NSEvent*)theEvent message of NSTextView (i.e. write your own descendant). In this event you will have key code in [theEvent keyCode].

For return there is a constant kVK_Return, for tab - kVK_Tab, etc.

You should add Carbon framework (and #import Carbon/Carbon.h) to access these constants.

Upvotes: 2

Related Questions