8
votes

I've subclassed a NSTextFieldCell (inside a NSTableView) to draw a custom foreground color when a cell (ie row) is selected (eg isHighlighted is true) and everything works fine.

The problem is when the table view loses the focus I want to draw the selected rows with a different color, how can I determine if the table view containing the cell isn't the first responder inside drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView?

My current code is

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView {
        NSColor* textColor = [self isHighlighted]
                 ? [NSColor alternateSelectedControlTextColor]
                 : [NSColor darkGrayColor];
}
3
I also really want an answer to this!Andrey Tarantsov

3 Answers

8
votes

The best way I've found that doesn't make you deal with responders (since sometimes the controlView's superview is the responder or some nonsense) is to use the editor:

BOOL isEditing = [(NSTextField *)[self controlView] currentEditor] != nil;

Easy as that!

4
votes

I've found a solution that uses the firstResponder, it is simple and seems efficient

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView {
        NSColor* textColor;

        if ([self isHighlighted]) {
            textColor = [[controlView window] firstResponder] == controlView 
                     ? [NSColor alternateSelectedControlTextColor]
                     : [NSColor yellowColor];
        } else {
            textColor = [NSColor darkGrayColor];
        }

        // use textColor
        ...
        ...
        [super drawWithFrame:cellFrame inView:controlView];
    }
2
votes

one more thing, the above code is perfect, however if you have multiple windows you will need to check if your window is key

        if (controlView && ([[controlView window] firstResponder] == controlView) && [[controlView window] isKeyWindow]) {
            [attributes setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
        }