Search code examples
cocoadelegatesnstextfield

When using NSTextFieldDelegate's – control:textView:doCommandBySelector: how do we allow/make normal performance of e.g. backspace?


In another SO thread (Execute an Action when the Enter-Key is pressed in a NSTextField?) I saw this suggested code for executing an action on pressing Enter in an NSTextField:

- (void)control:(NSControl *)control textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector
{
    NSLog(@"Selector method is (%@)", NSStringFromSelector( commandSelector ) );
    if (commandSelector == @selector(insertNewline:)) {
        //Do something against ENTER key

    } else if (commandSelector == @selector(deleteForward:)) {
        //Do something against DELETE key

    } else if (commandSelector == @selector(deleteBackward:)) {
        //Do something against BACKSPACE key

    } else if (commandSelector == @selector(insertTab:)) {
        //Do something against TAB key
    }
}

But when I use this, backspace and tab no longer work as normal. How to fix this?

I tried to comment on original post, but do not have sufficient reputation to post comments... TIA


Solution

  • control:doCommandBySelector: should return a bool. Return true if you have handled the event and you don't want the system to do any more, return false if you still want the system to execute its default implementation for the given selector. So you need to return false when the selector is the backspace or tab selector.