Dr.Kameleon
Dr.Kameleon

Reputation: 22810

Handle Double-click Mouse Event and Return Pressed for NSTableView

OK, what I need is pretty straightforward, though I can still find nothing specific.

I want to be able to :

How would you go about it?

P.S. I've had a look into NSTableViewDelegate specification, but I can't find anything useful.

Upvotes: 4

Views: 2305

Answers (3)

alobaili
alobaili

Reputation: 904

There is a way to handle the Return key without having to manually check for its key code. I'll show the answer in Swift, but it can be applied in Objective-C as well.

First, override keyDown(with:) in your view controller subclass that controls the table view and call interpretKeyEvents(_:):

override func keyDown(with event: NSEvent) {
    interpretKeyEvents([event])
}

Second, in the same view controller subclass, override insertNewLine(_:). This is called when the user presses the Return key:

override func insertNewLine(_ sender: Any?) {
    // Add your logic to handle the Return key being pressed
}

Here's an example:

class TableViewController: NSViewController {
    @IBOutlet var tableView: NSTableView!

    override func keyDown(with event: NSEvent) {
        interpretKeyEvents([event])
    }

    override func insertNewLine(_ sender: Any?) {
        guard tableView.selectedRow >= 0 else { return }
        print("Pressed Return on row \(tableView.selectedRow)")
    }
}

Upvotes: 0

maz
maz

Reputation: 8336

For the return event, subclass your NSTableView and override keyDown:

Swift 5.x:

    override func keyDown(with event: NSEvent) {
        if event.characters?.count == 1 {
            let character = event.keyCode
            switch (character) {
            // 36 is return
            case UInt16(36):
                print("return: \(event)")
            default:
                print("any other key: \(event)")
            }
        } else {
            super.keyDown(with: event)
        }
    }

Upvotes: 1

Anoop Vaidya
Anoop Vaidya

Reputation: 46533

For double click you need to do just these :

-(void)awakeFromNib{
    [self.tableView setDoubleAction:@selector(thisMethod)];
    //And if you wish to take selector dynamically, I guess you know how to do :)
}

-(void)thisMethod{
    NSLog(@"double clicked");
}

Upvotes: 5

Related Questions