我一直在寻找一个简单的例子,说明如何在文本字段中按下回车键时触发动作(或按钮)。
我应该对文本字段进行子类化吗?我需要设置一个委托来调用我需要的操作吗?有没有办法在我的主窗口控制器类中捕获事件?
如果您甚至可以为我指出正确的方向,那就太好了。谢谢。
我一直在寻找一个简单的例子,说明如何在文本字段中按下回车键时触发动作(或按钮)。
我应该对文本字段进行子类化吗?我需要设置一个委托来调用我需要的操作吗?有没有办法在我的主窗口控制器类中捕获事件?
如果您甚至可以为我指出正确的方向,那就太好了。谢谢。
已接受答案的评论中引用的网站......现在被网络主机“暂停”,并且谷歌缓存没有包含关键步骤的屏幕截图。
所以,这是我发现的另一种解决方案:
对于某些键(Enter、Delete、Backspace 等),Apple 不会调用正常的 controlTextDidEndEditing: 等方法。相反,Apple 为每个魔术键执行单独的选择器 - 但您可以使用一种方法来拦截它。
苹果官方文档在这里:
...但是如果消失/被移动,请将此方法添加到您的委托中:
- (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;
}
在我的情况下,我也想覆盖退格键 - 使用这种方法运行应用程序,我得到输出说选择器是“deleteBackward:”,所以我在那里添加了另一个 if 语句来对此做出反应。
要在您按 Enter 后执行操作,只需在您的窗口控制器中编写一个 IBAction 并连接到您的文本字段。如果您想在关注文本字段并离开需要设置委托的文本字段时调用您的方法(请参见此处)。
只需将控制器类的 IBAction 与文本字段连接即可。应在您按 Enter 或使用 Tab 或 Mouse 离开文本字段时调用该操作。
最好的办法是使用control + drag
你已经创建的动作,所以按下return
也会触发动作。
对于好奇,这里是如何实现-controlTextDidEndEditing:(NSNotification)obj
(如果你不关心只响应回车键)
AppDelegate.h:
// Conform to the protocol to avoid compiler warnings
@interface myClass : NSObject <NSTextFieldDelegate>
// Link up to the interface elements you want to trigger
@property (weak) IBOutlet NSTextField *myTextField;
@property (weak) IBOutlet NSButton *myButton;
// Create an action linked to myButton
- (IBAction)myButtonPressed:(id)sender;
// Advertise that you implement the method
- (void)controlTextDidEndEditing:(NSNotification *)obj;
AppDelegate.m:
@synthesize myTextField = _myTextField;
@synthesize myButton = _myButton;
// Make yourself the delegate
- (void)applicationDidFinishLoading:(NSNotification *)aMessage {
_myTextField.delegate = self;
}
// NSTextField objects send an NSNotification to a delegate if
// it implements this method:
- (void)controlTextDidEndEditing:(NSNotification *)obj {
if ([[obj object] isEqual:_textField]) {
[self myButtonPressed:nil]; // nil = sender
}
}
对我来说就像一个魅力。