keyDown:(NSEvent *)事件在焦点位于文本字段上时不会被调用 [英] keyDown:(NSEvent *)event is not invoked when the focus is on a text field

查看:327
本文介绍了keyDown:(NSEvent *)事件在焦点位于文本字段上时不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 NSPanel 子类中重写了 - (void)keyDown:(NSEvent *)event / p>

但是,只有当焦点不在面板中的 NSTextField 上时才会被调用。
然而,无论焦点是否在文本字段或面板上,我都需要捕获事件按下Enter按钮



如何确保它总是被调用?

解决方案

你确定需要捕获key down事件?



苹果在用 keyDown:控制的文档中的状态是最后的手段只有当代理的正常Cocoa体系结构不能满足你的需要时才使用。



如果目的是要按住回车按钮,注意这个事件在文本字段触发 textDidEndEditing 委托方法(或通知,如果你愿意的话)。



$ c> controlTextDidEndEditing:在您的 NSTextField 的代理中,您应该能够对事件做出反应。当字段编辑器结束编辑时,将发送此通知(和相关委托方法)。



如果您希望在字段编辑器结束编辑之前),您可以实现委托方法 control:textView:doCommandBySelector:,它允许您截取特定的键事件(例如返回键)并修改编辑器的行为。 / p>

例如:

   - :(NSControl *)控件textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector 
{
BOOL retval = NO;
if(commandSelector == @selector(insertNewline :)){
retval = YES; //处理

//按下newLine时需要做的事情
}
return retval;
}

有很多关于苹果网站的文档, 此处


I've overridden - (void)keyDown:(NSEvent *)event in my NSPanel subclass.

However it is invoked only if the focus is not on a NSTextField inside my panel. However I need to catch the event "Enter button pressed" regardless of if the focus is on the text field or the panel.

How to make sure it is always invoked?

解决方案

Are you sure that you need to catch the key down event for that?

Apple state in the docs that fiddling with keyDown: for controls is kind of a last resort, to be used only if the normal Cocoa architecture around delegates does not do what you want.

If the purpose is to catch the enter button pressed, notice that this event in a text field triggers the textDidEndEditing delegate method (or notification, if you prefer that).

So if you implement controlTextDidEndEditing: in a delegate for your NSTextField you should be able to react to the event. This notification (and the relative delegate method) is sent when the field editor ends editing.

If you prefer to catch the event one step earlier (before the field editor ends editing), you can implement the delegate method control:textView:doCommandBySelector: which lets you intercept specific key events (such as the return key) and modify the behaviour of the editor.

An example could be the following:

- (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector
{
    BOOL retval = NO;
    if (commandSelector == @selector(insertNewline:)) {
        retval = YES; // Handled

        // Do stuff that needs to be done when newLine is pressed
    }
    return retval;
}

There is a lot of documentation on Apple's site about it, for instance an introduction here.

这篇关于keyDown:(NSEvent *)事件在焦点位于文本字段上时不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆