Search code examples
cocoanstableviewnstextfield

mouseDown: in a custom NSTextField inside an NSTableView


I have a view-based NSTableView. Each view in the table has a custom text field.

I'd like to fire an action when the user clicks on the text field (label) inside the table's view (imagine having a hyperlink with a custom action in each table cell).

I've created a basic NSTextField subclass to catch mouse events. However, they only fire on the second click, not the first click.

I tried using an NSButton and that fires right away.

Here's the code for the custom label:

@implementation HyperlinkTextField

- (void)mouseDown:(NSEvent *)theEvent {
    NSLog(@"link mouse down");
}

- (void)mouseUp:(NSEvent *)theEvent {
    NSLog(@"link mouse up");
}

- (BOOL)acceptsFirstResponder {
    return YES;
}

- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent {
    return YES;
}
@end

Solution

  • It turned out that NSTableView and NSOultineView handle the first responder status for NSTextField instances differently than for an NSButton.

    The key to get the label to respond to the first click like a button is to overwrite [NSResponder validateProposedFirstResponder:forEvent:] to return YES in case of my custom text field class.

    Documentation:

    http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/NSResponder/validateProposedFirstResponder:forEvent: