5

I am trying to set a background colour on an NSTableCellView, but there doesn't seem to be an way to do this.

Therefor there must be another way to achieve this that i am not aware of, so, if anyone could enlighten me i would be most appreciative!

Thanks!

Gareth Jeanne
  • 1,410
  • 2
  • 19
  • 35
  • Try this: http://stackoverflow.com/questions/2879154/change-color-of-nstableviewcell – Matt Becker Jul 22 '13 at 18:41
  • 1
    Actually, the question suggested as a dupe is about setting the colour of an `NSTableViewCell` (subclass of `NSCell`), while the question is about the colour of an `NSTableCellView` (subclass of `NSView`). Two different things! When the old question was asked, view based tables did not exist in Cocoa. – Monolo Aug 21 '13 at 21:10

3 Answers3

12

A NSTableCellView is a NSView, and a NSView has a CALayer, and a CALayer has a backgroundColor. So...

myTableCellView.wantsLayer = YES;  // make the cell layer-backed
myTableCellView.layer.backgroundColor = [[NSColor redColor] CGColor]; // or whatever color you like
Caleb
  • 124,013
  • 19
  • 183
  • 272
  • @Caleb does anything need to be enabled on the tableview in interface builder to get this working? Its not working for me. XCode6 – Just a coder Jun 24 '15 at 17:36
  • 2
    @Jai A layer's background color needs to be a CGColor, so the above should probably be `...[[NSColor redColor] CGColor];`. I know that's the case on iOS, and from the docs it looks like the same situation on MacOS X. – Caleb Jun 24 '15 at 18:18
  • 1
    @Jai I had to enable layer with `myTableCellView.wantsLayer = true` – yuzer Oct 23 '15 at 08:11
  • 1
    A `NSView` **does not** have a `CALayer` by default. It will only have a `CALayer` if you explicitly tell it to have a `CALayer` (if you make it layer backed or layer hosting). Also your code sample is wrong as you assign a `NSColor` to a property of type `CGColor` (yields a compiler warning at built time and fails to work at runtime - won't even compile if you try that in Swift). – Mecki Jun 22 '16 at 13:44
  • @Mecki Thanks for your comments. Edited to fix the color problem. yuzer's comment above points out that you need to add a layer as well -- I'll include that edit too. – Caleb Jun 22 '16 at 16:17
1

You need to convert your NSColor object into a CGColor struct:

self.layer.backgroundColor = [[NSColor redColor] CGColor];
c9s
  • 1,888
  • 19
  • 15
1

for Swift 3, and based on Caleb's answer, this works for me:

cell.wantsLayer = true
cell.layer?.backgroundColor = NSColor.red.cgColor 

It took me ages to find this question and answer, and I'm most appreciative.

ICL1901
  • 7,632
  • 14
  • 90
  • 138