Switching the selected state of a TableView cell with the mouse

By default, NSTableView allows the user to clear row selections by clicking anywhere in an empty area of ​​the table. However, this is not always intuitive and sometimes even impossible (for example, when the table view actually does not have an empty area inside itself).

So, how do you allow the user to deselect a row by simply clicking on it again? In this case, the usual delegation methods are called (for example, -tableView:shouldSelectRow:), so you cannot capture a click on a row that is already selected in this way.

+4
source share
1 answer

NSTableView -mouseDown: :

- (void)mouseDown:(NSEvent *)theEvent {

    NSPoint globalLocation = [theEvent locationInWindow];
    NSPoint localLocation = [self convertPoint:globalLocation fromView:nil];
    NSInteger clickedRow = [self rowAtPoint:localLocation];

    BOOL wasPreselected = (self.selectedRow == clickedRow);

    [super mouseDown:theEvent];

    if (wasPreselected)
        [self deselectRow:self.selectedRow];

}
+3

All Articles