简体   繁体   中英

How to set a background color for NSTableCellView?

I've made an NSTableCellView in my nib, which has the textField occupying the entire space, and it works great for displaying text, and tracking the size of the column.

Now I want to be able to set a solid background color for it, in a specific case (ie, not for all cells). How do I do this?

I think it's like this question , except the solution there didn't do anything for me, and I can't come up with anything close to it that works, either.

I've tried making my -tableView:viewForTableColumn:row: method...

  • set the cellview.layer.backgroundColor
  • set cellview.wantsLayer=YES (and confirming that there's a layer)
  • set cellview.layer.opaque=YES and cellview.layer.opacity=1.0
  • set the cellview.textField.backgroundColor
  • set cellview.textField.drawsBackground=YES
  • in the nib, for the Table Cell View's Text Field, checked "Draws Background", and set the Background popup (which would be permanent for all table cells, not just for the ones I want in -tableView:viewForTableColumn:row:, but if this worked it would demonstrate to me that at least something here is capable of painting the background)

Since my text takes up the entire cell view, being able to set it on either the textField or the whole cell view would be fine.

This seems like it should be a simple setting somewhere, but nothing works. Do I need to subclass NSTableCellView just to have a background color?

I will recommend to create a subclass of NSTableCellView. It helps in creating a re-usable component(you can even add a gradient to make it look different) and segregating the responsibilities. You can use this simple code and change the class in NSTableCellView.

- (void)drawRect:(NSRect)dirtyRect
{        
    NSRect bounds = [self bounds];

    [[NSColor redColor] set];

        NSRectFill(bounds);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM