How to determine when NSTextFieldCell isHighlighted has no focus?

I subclassed an NSTextFieldCell (inside an NSTableView) to draw its own foreground color when a cell (i.e. row) is selected (e.g. isHighlighted is true) and everything works fine.

The problem is that the table view loses focus. I want to draw the selected rows with a different color, how can I determine if the table view containing this cell is not the first responder inside drawWithFrame: (NSRect) cellFrame inView: (NSView *) ControlView

My current code

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView { NSColor* textColor = [self isHighlighted] ? [NSColor alternateSelectedControlTextColor] : [NSColor darkGrayColor]; } 
+7
source share
3 answers

The best way I found that does not make you deal with respondents (since sometimes the controlView supervisor is a responder or some kind of nonsense) is to use an editor:

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

Just like that!

+5
source

I found a solution that uses 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]; } 
+3
source

one more thing, the code above 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]; } 
+2
source

All Articles