Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a row in an NSTableView when clicking on an NSTextView inside an NSTableCellView?

I have a view-based single-column NSTableView. Inside my NSTableCellView subclass I have an NSTextView which is selectable, but not editable.

When the user clicks on the NSTableCellView directly, the row highlights properly. But when the user clicks on the NSTextView inside that NSTableCellView, the row does not highlight.

How do I get the click on the NSTextView to pass to the NSTableCellView so that the row highlights?

Class hierarchy looks like: NSScrollView > NSTableView > NSTableColumn > NSTableCellView > NSTextView

like image 379
sam Avatar asked Apr 17 '12 02:04

sam


1 Answers

Here's what I ended up doing. I made a subclass of NSTextView and overrode mouseDown: as follows...

- (void)mouseDown:(NSEvent *)theEvent
{
    // Notify delegate that this text view was clicked and then
    // handled the click natively as well.
    [[self myTextViewDelegate] didClickMyTextView:self];
    [super mouseDown:theEvent];
}

I'm reusing NSTextView's standard delegate...

- (id<MyTextViewDelegate>)myTextViewDelegate
{
    // See the following for info on formal protocols:
    // stackoverflow.com/questions/4635845/how-to-add-a-method-to-an-existing-protocol-in-cocoa
    if ([self.delegate conformsToProtocol:@protocol(MyTextViewDelegate)]) {
        return (id<MyTextViewDelegate>)self.delegate;
    }
    return nil;
}

And in the header...

@protocol MyTextViewDelegate <NSTextViewDelegate>
- (void)didClickMyTextView:(id)sender;
@end

In the delegate, I implement didClickMyTextView: to select the row.

- (void)didClickMyTextView:(id)sender
{
    // User clicked a text view. Select its underlying row.
    [self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:[self.tableView rowForView:sender]] byExtendingSelection:NO];
}
like image 137
sam Avatar answered Sep 21 '22 08:09

sam