Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

objective c - NSTextField enter to trigger action

I've been looking all over for a simple example of how to have an action (or button) be triggered when the enter key is hit in the text field.

Should I subclass the text field? Would I need to set a delegate to call the action I need? Is there a way to catch the event in my main window controller class?

If you could even just point me to the right direction that would be great. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The site that is referenced in the comments to the accepted answer ... is now "SUSPENDED" by the webhost, and Google cache doesn't have the screenshot that contains the key step.

So, here's an alternative solution I found that:

  1. works perfectly
  2. does NOT require subclassing

For some keys (Enter, Delete, Backspace, etc), Apple does NOT invoke the normal controlTextDidEndEditing: etc methods. Instead, Apple does individual selectors for each magic key - but there's a method you can use to intercept it.

Apple's official docs here:

https://developer.apple.com/library/mac/documentation/TextFonts/Conceptual/CocoaTextArchitecture/TextEditing/TextEditing.html#//apple_ref/doc/uid/TP40009459-CH3-SW31

...but in case that vanishes / gets moved, add this method into your delegate:

- (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector
{           
    BOOL retval = NO;

    if (commandSelector == @selector(insertNewline:)) {

        retval = YES; // causes Apple to NOT fire the default enter action

        // Do your special handling of the "enter" key here

    }

    NSLog(@"Selector = %@", NSStringFromSelector( commandSelector ) );

    return retval;  
}

In my case, I wanted to override the backspace key too - running the app with this method, I got output saying that the selector was "deleteBackward:", so I added another if-statement in there to react to that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...