Get keyDown event for an NSTextField

3 Solutions Collect From Internet About “Get keyDown event for an NSTextField”

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.

Subclass the text field


@interface LQRestrictedInputTextField : NSTextField 


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 = @[@" ",@"(",@")",@"[",@"]",@":",@";",@"\'",@"\"",@".",@"<",@">",@",",@"{",@"}",@"|",@"=",@"+",@"-",@"_",@"?",@"#",

                if([[NSCharacterSet alphanumericCharacterSet] characterIsMember:character] || character == NSCarriageReturnCharacter || character == NSTabCharacter || character == NSDeleteCharacter || [validNonAlphaNumericArray containsObject:characterString ] ) { //[NSCharacterSet alphanumericCharacterSet]
                }  else {
                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.

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

    NSTextView *textView=[notification object];

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

in .h

@interface MyTextField : NSTextField <NSTextFieldDelegate>

in .m

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

Add UITextFieldDelegate to your .h like this

@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.