简体   繁体   中英

Overriding keyDown causes issues to a NSTableView

In my NSTableView subclass MyTableView I've overwritten

- (void) keyDown:(NSEvent *)event {

    if ( [event keyCode] == 51 || [event keyCode] == 117 ) {
        [super keyDown:event];
        return;
    }

}

51 is the code for the delete button. I'm expecting the table view to delete the selected item as before the subclassing.

The event is correctly caught and the keyDown method of the superclass is invoked. However, the item is not deleted anymore. Why ?

Thanks

Recommend you override keyDown: in your window class.

-(void) keyDown: (NSEvent *) event
{
    NSString *chars = [event characters];
    unichar character = [chars characterAtIndex: 0];
    if (character == NSDeleteCharacter || character == NSBackspaceCharacter) 
    {
        NSTableView* view = (NSTableView*)[self firstResponder];
        if(view == theTableView)
        {
        // do something to delete the item from your data model and reload the tableview
        }
    }
} 

If you are trying just to invoke a specific method when the Delete key is pressed, I'd suggest overriding the -deleteBackward: method (part of NSResponder ), because it isolates this interception more specifically. It also manages the problem of remapped keyboards, macros, etc.

There's also -deleteForward for the delete key instead of the backspace key.

-(void)deleteBackward:(id)sender
{
     // do my override here
     // do this only if super implements deleteBackward:
     [super deleteBackward: sender]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM