1
votes

I have view-based NSTableView with custom NSTextField subclass instances to draw the row labels.

Depending on if a row is selected (highlighted) I want to change the background color of my custom text field.

How do I know in drawRect:(NSRect)dirtyRect of my text field if the parent table row is selected?

The text field doesn't even know that it is part of a table view (and shouldn't have to).

If I put a plain NSTextField into a table view it automatically changes its font color based on the row selection status so it must be somehow possible for a text field to know if it is selected/highlighted or now.

1

1 Answers

0
votes

The table view is a parent view of the views in the cell view. So you can iterate up the view hierarchy in the drawRect method to find the parent table view. And with it check if the row containing the custom NSTextField is selected.

override public func drawRect(dirtyRect: NSRect) {
    var backgroundColor = NSColor.controlColor() //Replace by the non selected color
    var parentView = superview
    while parentView != nil {
        if let tableView = parentView as? NSTableView {
            let row = tableView.rowForView(self)
            if tableView.isRowSelected(row) {
                backgroundColor = NSColor.alternateSelectedControlColor() //Replace by the selected background color
            }
            break
        }
        parentView = parentView?.superview
    }
    //Perform the drawing with the backgroundColor
   // ...
}