Setting the background color for NSView

Foreword.

So in 2016, I was started working as a software developer. My first project was targeted at macOS. It was an awesome and very interesting time: I was young, hungry to learn technology, but the salary was small, there was not enough money to live on.
Since then, I like macOS.

Setting the background color for NSView.

NSView does not have a property for setting the background color. The solution is to set the background color for the view layer. By default, an NSView does not have a layer attached to it. You must set wantLayer to true (by default wantLayer is false) to display the layer in the view.

import Cocoa

let myView = NSView(frame: .init(origin: .zero, size: CGSize(width: 50, height: 50)))
myView.wantsLayer = true
myView.layer?.backgroundColor = NSColor.green.cgColor

To make a convenience can add a background color as an extension to NSView:

extension NSView {
    
    var backgroundColor: NSColor? {
        set {
            wantsLayer = true
            layer?.backgroundColor = newValue?.cgColor
        }
        get {
            guard let backgroundColor = layer?.backgroundColor else { return nil }
            return NSColor(cgColor: backgroundColor)
        }
    }
}

Recommended links:

https://developer.apple.com/documentation/appkit/nsview/1483695-wantslayer

Thanks for reading! See you soon. 👋