How to change the background colour of an NSView in OS X 10.8 onwards (Xcode; update Swift 3, Xcode 8)


** Jump to Swift 3 code **

In iOS changing the background colour of a UIView is a trivial thing to achieve. We simply write:

myView.backgroundColor = [UIColor yellowColor];  // myView is a UIView

Changing the background colour of an NSWindow

While it is as simple to change the background colour of a window in OS X

[self.window setBackgroundColor:[NSColor yellowColor]];

it is slightly more complicated to change the background colour of an NSView, but not that much more complicated from OS X 10.8 onwards.

Changing the background colour of an NSView from OS X 10.8 onwards

There are three steps. The first of which is to import the Quartz Core framework in the relevant header file:

#import <QuartzCore/QuartzCore.h>

The second is to call the setWantsLayer: method in order to enable layer support

[myView setWantsLayer:YES]; // myView is an NSView

And finally we can write, just as we might in iOS if we were changing the background colour of a layer:

myView.layer.backgroundColor = [NSColor yellowColor].CGColor;

and that's all there is to it.

NSView Pre-OS X 10.8

If you want to support pre-10.8 versions then take a look at the responses to the question Best way to change the background color for an NSView on StackOverflow.

Swift 3, Xcode 8

import QuartzCore

let aView = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
aView.wantsLayer = true
aView.layer?.backgroundColor = NSColor.yellow.cgColor

Comments