I'm trying to detect when a mouse click occurs in an NSTableView, and when it does, to determine the row and column of the cell that was clicked.
So far I've tried to use NSTableViewSelectionDidChangeNotification, but there are two problems:
Is there a better (and correct) way of doing this?
There is a simple way.
Tested with Swift 3.0.2 on macOS 10.12.2 and Xcode 8.2.1
Let
tableView.action = #selector(onItemClicked)
Then
@objc private func onItemClicked() { print("row \(tableView.clickedRow), col \(tableView.clickedColumn) clicked") }
To catch the user clicking a row (only, when the user clicks a row, not when it is selected programmatically) :
Subclass your NSTableView and declare a protocol
MyTableView.h
@protocol ExtendedTableViewDelegate <NSObject> - (void)tableView:(NSTableView *)tableView didClickedRow:(NSInteger)row; @end @interface MyTableView : NSTableView @property (nonatomic, weak) id<ExtendedTableViewDelegate> extendedDelegate; @end
MyTableView.m
Handle the mouse down event (note, the delegate callback is not called when the user clicks outside, maybe you want to handle that too, in that case, just comment out the condition "if (clickedRow != -1)
")
- (void)mouseDown:(NSEvent *)theEvent { NSPoint globalLocation = [theEvent locationInWindow]; NSPoint localLocation = [self convertPoint:globalLocation fromView:nil]; NSInteger clickedRow = [self rowAtPoint:localLocation]; [super mouseDown:theEvent]; if (clickedRow != -1) { [self.extendedDelegate tableView:self didClickedRow:clickedRow]; } }
Make your WC, VC conform to ExtendedTableViewDelegate.
@interface MyViewController : DocumentBaseViewController<ExtendedTableViewDelegate, NSTableViewDelegate, NSTableViewDataSource>
set the extendedDelegate of the MyTableView to your WC, VC (MyViewController)
somewhere in MyTableView.m
self.myTableView.extendedDelegate = self
Implement the callback in delegate (MyViewController.m)
- (void)tableView:(NSTableView *)tableView didClickedRow:(NSInteger)row { // have fun }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With