Search code examples
swiftcocoafontssubviewtextcolor

How to keep functionality of Control Text Color in subview?


I have a NSTableview with labels inside and outside of a subview. When a row is selected, the color of the text in the textlabel should turn white.

enter image description here

In this case, Status and Rank both have Control Text Color, but only Status turns white when selected because it is not in a subview.

enter image description here

Is it possible to keep this functionality of the Control Color in a textlabel even when it is in a subview?

enter image description here


Solution

  • You have to manually code that, either by adding an extension or declaring a subclass and override the setBackgroundStyle, since NSTableView won't recursively call the function down to its subviews.

    extension NSTableView {
        func setBackgroundStyle(_ newValue: NSBackgroundStyle) {
            for view in self.subviews {
                view.setBackgroundStyle(newValue)
            }
        }
    }
    
    extension NSTextField {
        func setBackgroundStyle(_ newValue: NSBackgroundStyle) {
            switch newValue {
                case NSBackgroundStyleDark:
                    self.textColor = NSColor.controlHighlightColor
                case NSBackgroundStyleLight:
                    self.textColor = NSColor.controlColor
            }
        super.setBackgroundStyle(newValue)
        }
    }