Override keydownevent in NSTextfield

I created a subclass of nstextfield and I override the keydown event, but my code does not work, then I override the keyup event and the code works fine. My code (doesn't work):

-(void)keyDown:(NSEvent *)event { NSLog(@"Key released: %hi", [event keyCode]); if ([event keyCode]==125){ [[self window] selectKeyViewFollowingView:self]; } if ([event keyCode]==126){ [[self window] selectKeyViewPrecedingView:self]; } } 

My activation code (it works):

 -(void)keyUp:(NSEvent*)event {if ([event keyCode]==125){ [[self window] selectKeyViewFollowingView:self]; } if ([event keyCode]==126){ [[self window] selectKeyViewPrecedingView:self]; } if ([event keyCode]==36){ [[self window] selectKeyViewFollowingView:self]; } } 

I do not see where the problem is with my code. Any suggestion will be accepted.

EDIT: I read that you need to subclass NSTextView instead of NSTextField.

+6
source share
4 answers

The keydown event cannot be overridden in NSTextField, if you want, you can override the keydown event of the superview, or you can use NSTextView or just override the keyup event in NSTextField

+8
source

You can do this without a subclass using the NSTextFieldDelegate methods:

As @ Darren Inksetter said, you can use control:textView:doCommandBySelector:

First declare NSTextFieldDelegate in your interface tag. Then we implement the method:

 - (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector { if( commandSelector == @selector(moveUp:) ){ // Do yourthing here, like selectKeyViewFollowingView return YES; // Return YES means don't pass it along responders chain. Return NO if you still want system action on this key. } if( commandSelector == @selector(moveDown:) ){ // Do the same with the keys you want to track return YES; } return NO; } 
+9
source

Swift 5 example.

 func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { switch commandSelector { case #selector(moveUp(_:)): impl.tableView.doCommand(by: commandSelector) return true case #selector(moveDown(_:)): impl.tableView.doCommand(by: commandSelector) return true default: return false } } 
0
source

Source: https://habr.com/ru/post/887468/


All Articles