NSTableView: detecting a mouse click together with the row and column

后端 未结 6 537
Happy的楠姐
Happy的楠姐 2020-12-08 01:10

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

6条回答
  •  抹茶落季
    2020-12-08 01:43

    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 
    
    - (void)tableView:(NSTableView *)tableView didClickedRow:(NSInteger)row;
    
    @end
    
    @interface MyTableView : NSTableView
    
    @property (nonatomic, weak) id 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
    

    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
    }
    

提交回复
热议问题