我现在有一个小问题.我想在NSTextField中按下Enter键时执行一个方法.用户应该能够输入他的数据,并且一旦他按下回车键就应该执行计算方法.
您可以通过设置文本字段的操作来完成此操作.在IB中,将文本字段的选择器连接到控制器或任何呈现您要使用的IBAction的对象.
要在代码中设置它,请向NSTextField发送setTarget:
消息和setAction:
消息.例如,如果您在代码中的控制器对象上设置此项,并且textField出口名为myTextField:
- (void)someAction:(id)sender { // do something interesting when the user hitsin the text field } // ... [myTextField setTarget:self]; [myTextField setAction:@selector(someAction:)];
你必须这样做
对于某些键(Enter,Delete,Backspace等)
self.textfield.delegate = self;
然后实现此方法
- (BOOL)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 } // return YES if the action was handled; otherwise NO }
在您的委托(NSTextFieldDelegate)中,添加以下内容:
-(void)controlTextDidEndEditing:(NSNotification *)notification { // See if it was due to a return if ( [[[notification userInfo] objectForKey:@"NSTextMovement"] intValue] == NSReturnTextMovement ) { NSLog(@"Return was pressed!"); } }
在斯威夫特3版@ M.ShuaibImran的解决方案:
首先将ViewController子类化为:NSTextFieldDelegate
class MainViewController: NSViewController, NSTextFieldDelegate { ... }
将textField委托分配给viewDidLoad()中的ViewController:
self.textField.delegate = self
包括处理键盘响应者的NSTextFieldDelegate方法:
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { if (commandSelector == #selector(NSResponder.insertNewline(_:))) { // Do something against ENTER key print("enter") return true } else if (commandSelector == #selector(NSResponder.deleteForward(_:))) { // Do something against DELETE key return true } else if (commandSelector == #selector(NSResponder.deleteBackward(_:))) { // Do something against BACKSPACE key return true } else if (commandSelector == #selector(NSResponder.insertTab(_:))) { // Do something against TAB key return true } else if (commandSelector == #selector(NSResponder.cancelOperation(_:))) { // Do something against ESCAPE key return true } // return true if the action was handled; otherwise false return false }
它非常简单,您可以直接从UI编辑器进行操作
右键单击Text Feild,将Action引用拖动到按钮,如下面的屏幕截图所示
现在它将为您提供一些选项,如下面的屏幕截图所示,您需要选择执行单击
现在看起来应该是这样的
注意:按Tab
或Enter
按键后将立即引发事件.如果您希望仅在用户按下Enter
键时引发操作,则必须进行设置.转到Attribute inspector
并更改Action属性,Send on Enter only
如下面的屏幕截图所示