Javier Beltrán
Javier Beltrán

Reputation: 756

Override keydownevent in NSTextfield

I made a subclass of the nstextfield and i override the keydown event but my code doesn't work, then i override de keyup event and the code works perfectly. My keydown 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 keyup 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 don't see where is the problem with my keydown code. Any suggest will be accepted

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

Upvotes: 7

Views: 4825

Answers (4)

eonil
eonil

Reputation: 85975

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
        }
    }

Upvotes: 6

anhdat
anhdat

Reputation: 465

You can do it without subclassing by using NSTextFieldDelegate methods:

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

First, declare NSTextFieldDelegate in your interface tag. Then 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's action on this key.
    }
    if( commandSelector == @selector(moveDown:) ){
        // Do the same with the keys you want to track
        return YES;
    }
    return NO;
}

Upvotes: 14

Javier Beltrán
Javier Beltrán

Reputation: 756

The keydown event can't be overriden in a NSTextField, if you want , you could override the keydown event of the super view or you could use a NSTextView or just override the keyup event in the NSTextField

Upvotes: 9

Related Questions