xcode 获取 NSTextField 的 keyDown 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8868489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:00:06  来源:igfitidea点击:

Get keyDown event for an NSTextField

xcodemacoscocoaeventskeydown

提问by Laurent Crivello

In xcode last version, I am trying to get the keyDown event of an NSTextField. However, despite following multiple tutorials on the internet (delegates, controllers...), I still can't receive it.

在 xcode 上一个版本中,我试图获取 NSTextField 的 keyDown 事件。但是,尽管在互联网上学习了多个教程(委托、控制器......),我仍然无法接收它。

Any easy hint for me ?

对我有什么简单的提示吗?

Thanks !

谢谢 !

回答by Scott Jenkins

I got sick of all the non answers to do it some other way people so I put my nose down and figured out a way to make this work. This isn't using keydown event directly but it is using the keydown in the block. And the behavior is exactly what I wanted.

我厌倦了人们以其他方式做这件事的所有非答案,所以我低下头并想出了一种方法来使这项工作发挥作用。这不是直接使用 keydown 事件,而是使用块中的 keydown。而这种行为正是我想要的。

Subclass the text field

子类化文本字段

.h

。H

@interface LQRestrictedInputTextField : NSTextField 

.m

.m

In the become first responder setup a local event

在成为第一响应者设置一个本地事件

static id eventMonitor = nil;

- (BOOL)becomeFirstResponder {
    BOOL okToChange = [super becomeFirstResponder];
    if (okToChange) {
        [self setKeyboardFocusRingNeedsDisplayInRect: [self bounds]];

        if (!eventMonitor) {
            eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event) {

                NSString *characters = [event characters];
                unichar character = [characters characterAtIndex:0];
                NSString *characterString=[NSString stringWithFormat:@"%c",character];

                NSArray *validNonAlphaNumericArray = @[@" ",@"(",@")",@"[",@"]",@":",@";",@"\'",@"\"",@".",@"<",@">",@",",@"{",@"}",@"|",@"=",@"+",@"-",@"_",@"?",@"#",
                                                   @(NSDownArrowFunctionKey),@(NSUpArrowFunctionKey),@(NSLeftArrowFunctionKey),@(NSRightArrowFunctionKey)];

                if([[NSCharacterSet alphanumericCharacterSet] characterIsMember:character] || character == NSCarriageReturnCharacter || character == NSTabCharacter || character == NSDeleteCharacter || [validNonAlphaNumericArray containsObject:characterString ] ) { //[NSCharacterSet alphanumericCharacterSet]
                }  else {
                    NSBeep();
                    event=nil;
                }
                return event;
            } ];

        }
    }
    NSLog(@"become first responder");
    return okToChange;
}

remove the event once the textfield editing ends

文本字段编辑结束后删除事件

Also if you're using ARC I noticed you might need to assign the textview string to the stringValue. I nslog'd the stringValue and the value was retained. Without the nslog I had to assign the notification object string to the stringValue to keep it from getting released.

另外,如果您使用的是 ARC,我注意到您可能需要将 textview 字符串分配给 stringValue。我记录了 stringValue 并保留了该值。如果没有 nslog,我必须将通知对象字符串分配给 stringValue 以防止它被释放。

-(void) textDidEndEditing:(NSNotification *)notification {
    [NSEvent removeMonitor:eventMonitor];
    eventMonitor = nil;

    NSTextView *textView=[notification object];
    self.stringValue=textView.string;
}

回答by Justin Boo

You can subclass NStextField and use keyUp that works for NSTextField.

您可以继承 NStextField 并使用适用于 NSTextField 的 keyUp。

in .h

在.h

@interface MyTextField : NSTextField <NSTextFieldDelegate>

in .m

在.m

-(void)keyUp:(NSEvent *)theEvent {
    NSLog(@"Pressed key in NStextField!");
}

回答by Darren

Add UITextFieldDelegate to your .h like this

像这样将 UITextFieldDelegate 添加到您的 .h

@interface ViewController :  UIViewController <UITextFieldDelegate> {

Then you can use this to detect every key press in a text field

然后您可以使用它来检测文本字段中的每个按键

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

Return YES to allow the character that was pressed to be inserted into the field but you can add whatever code you need in here.

返回 YES 以允许将按下的字符插入到该字段中,但您可以在此处添加您需要的任何代码。