How can I make the Tab key move focus out of a NSTextView?
Asked Answered
M

3

16

I'm using an NSTextView to allow multi-line input. However, due to the nature of my app, users will be more comfortable moving to the next input element when they press TAB.

How can I make TAB exit the NSTextView, while keeping the newline behaviour of the Enter key?

Murky answered 20/3, 2010 at 17:47 Comment(0)
R
23

You could implement -textView:doCommandBySelector: in your text view's delegate:

- (BOOL)textView:(NSTextView *)aTextView doCommandBySelector:(SEL)aSelector {
    if (aSelector == @selector(insertTab:)) {
        [[aTextView window] selectNextKeyView:nil];
        return YES;
    }

    return NO;
}

See http://developer.apple.com/documentation/Cocoa/Reference/NSTextViewDelegate_Protocol

Ruel answered 21/3, 2010 at 4:52 Comment(1)
Very nice approach. You could also check for insertBacktab: and call selectPreviousKeyView: in similar fashion.Meristic
F
4

You'll need to implement this in a subclass.

I wrote such a subclass for Translate Text. You're welcome to use it under its BSD license. Here's the header and the implementation file.

… while keeping the newline behaviour of the Enter key?

My main purpose was to send an action to a target when the user presses Enter, and I also have it drop focus from the view. However, both are explicit statements in the code; you can simply comment that code out or delete it.

Farika answered 20/3, 2010 at 21:44 Comment(1)
The key code for Enter is defined in the headers as kVK_ANSI_KeypadEnter. Similarly, Tab is kVK_Tab.Producer
C
1

Swift version of the answers of Wevah & Quinn:

func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    switch commandSelector {
    case #selector(NSResponder.insertTab(_:)):
        textView.window?.selectNextKeyView(nil)
        return true
    case #selector(NSResponder.insertBacktab(_:)):
        textView.window?.selectPreviousKeyView(nil)
        return true
    default:
        return false
    }
}
Cryptonymous answered 14/5, 2022 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.