Search code examples
swiftcocoaappkit

Background color of NSGridview


I tried to set the background color of an NSGridView by subclassing it and overriding its draw method like this:

class GridViewGreen: NSGridView
{ override func draw(_ dirtyRect: NSRect)
  { super.draw(dirtyRect)

    let color = NSColor.green
    let bp = NSBezierPath(rect: dirtyRect)
    color.set()
    bp.stroke()

    print("drawing GridViewGreen")
  }
}

But the draw method is never called.


Solution

  • Update: Preferably take catlan's answer if possible. He is right in that NSGridView isn't really meant for rendering and this approach will more or less force it down that path.

    At this point, pretty much every Cocoa application should be layer-backing their views and NSGridView and NSStackView aren't any different. Simply set the background color on the layer.

    let gridView = NSGridView(views: [[view1, view2]])
    gridView.wantsLayer = true
    gridView.layer?.backgroundColor = NSColor.red.cgColor