Search code examples
xcodemacoshighlightnstextfieldnstablecellview

How can you change the highlight color of a NSTextField within a NSTableCellView?


In storyboard when I set the Text Color of a NSTextField within a NSTableCellView to Control Text Color the color becomes black and when the cell is selected/highlighted it will become white. When you deselect the color will return to black. You get all this behavior for free.

I created another textfield under the default it is similar to that of iOS (see the label Game in the image below). I changed the Text Color to the gray and that all works. However, when I now select/highlight the cell, the color remains gray and does not swap to white. How can I get such behavior through Storyboard? And if not possible, through code?

enter image description here


Solution

  • There is no automatic way to get what you want. The automatic behavior you're seeing with the black label is implemented by NSTextFieldCell (or one of its superclasses, like NSCell). It is triggered by the setting of the cell's backgroundStyle to NSBackgroundStyleDark. The cell's backgroundStyle is set by NSTableCellView when its own backgroundStyle is set. NSTableCellView's backgroundStyle is set by NSTableRowView when its interiorBackgroundStyle changes, which happens when its other properties, like selected and emphasized, are set.

    Anyway, the cell only automatically changes the color it uses to draw if its textColor is [NSColor controlTextColor] or has equivalent RGB values. So, it doesn't work for your gray labels.

    You could implement a custom subclass of NSTableCellView or NSTextField. Your class would implement (override, for a subclass of NSTableCellView) -setBackgroundStyle:. In your method, you can check what style is being set and change the text field's textColor. If it's an override, call through to super. (Although NSTextField does not currently implement a backgroundStyle property, it probably will in the future. Apple has said they will be adding cover methods to controls for methods which currently only exist on cell classes. So, you should do if ([NSTextField instancesRespondToSelector:@selector(setBackgroundStyle:)]) [super setBackgroundStyle:backgroundStyle]; to be future-safe.)