Technical Q&A QA1454

How to make NSTextField accept tab, return and enter keys.

Q:  How do I make NSTextField accept the tab key, as well as return and enter keys as line-breaks?

A: It's worth noting that NSTextField supports new line breaks by using Option-Return or Option-Enter. But under most circumstances the easiest solution would be to use NSTextView instead.

So you need to ask yourself "why" you want to keep using NSTextField. Here is a list of possible reasons:

Delegate Method

Should you decide to keep using NSTextField, allowing the tab key and/or allowing enter and return keys for line-breaks can be achieved by implementing the following delegate method:

- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector;

The method name doCommandBySelector means "attempt to perform the indicated method". It originates or is driven from the NSResponder class.

This delegate method is a part of NSControl, so it is found in NSControl.h, not in NSTextField.h.

Listing 1  Example delegate method for NSTextField.

- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
{
    BOOL result = NO;
 
    if (commandSelector == @selector(insertNewline:))
    {
        // new line action:
        // always insert a line-break character and don’t cause the receiver to end editing
        [textView insertNewlineIgnoringFieldEditor:self];
        result = YES;
    }
    else if (commandSelector == @selector(insertTab:))
    {
        // tab action:
        // always insert a tab character and don’t cause the receiver to end editing
        [textView insertTabIgnoringFieldEditor:self];
        result = YES;
    }
 
    return result;
}

For more information on NSTextField and NSTextView refer to Cocoa Text Architecture Guide.



Document Revision History


DateNotes
2014-05-12

Updated link to Cocoa Text Architecture Guide.

2006-10-09

New document that describes how to make the NSTextField control accept tab, return and enter keys by using the control's dispatch delegate method.