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:

  • It may not be obvious to users that Option-Return and Option-Enter are available to them.

  • You want to keep using the conveniences and features of NSTextField's super class NSControl.

  • NSTextField is light-weight compared to NSTextView.

  • NSTextField supports horizontal scrolling, by default NSTextView does not and requires extra work to avoid text wrapping.

  • You want the flexibility of using the target/action scheme, often configured in InterfaceBuilder.

  • You may simply want to just allow the tab key and are not concerned with line-breaks.

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.

Note: When implementing this delegate method in your own object you should set your object up as the "delegate" for this NSTextField.

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;
}

Note: Notice Listing 1 uses two action methods: insertNewline:, insertTab:. You can refer to more of these types of action methods in NSResponder.h.

For more information on NSTextField and NSTextView refer to -

Text Editing Programming Guide for Cocoa: "Working with the Field Editor".

Back to Top 

Document Revision History

DateNotes
2006-10-09First Version

Posted: 2006-10-09


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.