nstableviewnsviewnstableviewcell

What's the NSView version of NSCell's highlighted property?


I'm migrating a cell-based NSTableView to be view-based. With NSCell, to determine if a cell was highlighted (e.g., to draw the text in white instead of black), I looked at the NSCell highlighted property.

What's the NSView version of this? I can't find anything like this in the docs.


Solution

  • The easiest way to do this is to simply subclass NSTableCellView. All the documentation says that you can subclass either NSTableCellView or NSView, e.g., Table View Programming Guide for Mac:

    Drag an NSTableCellView object (or a custom view) from the object library to the appropriate column in the table view. ... Typically, the view class is a subclass of NSTableCellView.

    It doesn't say what this is, or why you'd want to use it. It looks like an NSView which has an NSTextField and an NSImageView, and that's it -- so if you're not making a view that has these, it's tempting to ignore this class and just subclass NSView.

    Interestingly, though, if you have any NSTextFields in an NSTableCellView (even if you don't use the textField property for this!), they automatically use the correct light/dark coloring.

    In particular, it seems that the backgroundStyle property of NSTableCellView is what causes the text value to actually change. The documentation says:

    The default implementation automatically forwards calls to all subviews that implement setBackgroundStyle: or are an NSControl, which have NSCell classes that respond to setBackgroundStyle:.

    NSTextField is an NSControl with an NSCell, of course, so it gets this called on it.

    While it's not exactly clear in Apple's documentation (what does "this" refer to?), it seems that NSTableView calls -setBackgroundStyle: on any view that defines it. So if you don't want to subclass NSTableCellView, you can alternatively just add a property to your own NSView:

    var backgroundStyle: NSBackgroundStyle
    

    and have your drawing code use that.