Re: Background color on NSView?

Gary L. Wade

What I do is write an extension on NSView with a setter and getter for backgroundColor that calls through to the view's layer property's backgroundColor, calling wantsLayer before doing so in the setter. Note that the layer won't be instantiated during an initWithCoder call prior to 10.13; you'll need to redo this in 10.12 and earlier. I find most cases I can get around this with a dispatch async to re-call the setter if I have a nil layer after setting wantsLayer to true; eventually it sticks, and I haven't seen too many significant issues, but you need to be sure that works for you. Apple fixed this initWithCoder/wantsLayer bug in 10.13, at least it's still fixed for now. I do this for all the good stuff, cornerRadius, borderColor, borderWidth, etc., just like in iOS on UIView.
Gary L. Wade

On Aug 29, 2017, at 7:51 AM, Dave <dave@...> wrote:

Hi All,

I’ve just realised that NSView don’t have a background colour. I remember hitting this a long while ago and got around it by using a layer and adding a “setBackgroundColor” method to my Class.

Does anyone know how to do this? I can’t find the code or a reference to it now.

All the Best


As you may have gathered I’m porting code between iOS and Mac and Vice Versa, if anyone else is doing this kind of thing, I’ve found the following Macro’s VERY handy:


#define LTWPlatformKitHeaderFile <UIKit/UIKit.h>

#define LTWNativeViewControllerClass UIViewController
#define LTWNativeViewClass UIView
#define LTWNativeImageClass UIImage
#define LTWNativeImageViewClass UIImageView
#define LTWNativeColorClass UIColor
#define LTWNativeBezierClass UIBezierPath

#define LTWNativeViewIdentifierMethod accessibilityIdentifier

#define LTWNativePointType CGPoint
#define LTWNativeSizeType CGSize
#define LTWNativeRectType CGRect


#define LTWPlatformKitHeaderFile <AppKit/AppKit.h>

#define LTWNativeViewControllerClass NSViewController
#define LTWNativeViewClass NSView
#define LTWNativeImageClass NSImage
#define LTWNativeImageViewClass NSImageView
#define LTWNativeColorClass NSColor
#define LTWNativeBezierClass NSBezierPath

#define LTWNativeViewIdentifierMethod identifier

#define LTWNativePointType NSPoint
#define LTWNativeSizeType NSSize
#define LTWNativeRectType NSRect




Join to automatically receive all group messages.