Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine when NSTextFieldCell isHighlighted has no focus?

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];
}
like image 577
dafi Avatar asked Jul 29 '11 15:07

dafi


3 Answers

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!

like image 142
Sam Soffes Avatar answered Oct 24 '22 06:10

Sam Soffes


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];
    }
like image 34
dafi Avatar answered Oct 24 '22 05:10

dafi


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];
        }
like image 45
Klajd Deda Avatar answered Oct 24 '22 06:10

Klajd Deda