I have this code in my ViewController. The view I'm adding programatically is nowhere to be seen however.
override func viewDidLoad() {
    super.viewDidLoad()
    let f: NSRect = NSMakeRect(0, 0, 200, 200)
    let v: NSView = NSView(frame: f)
    v.layer?.backgroundColor = NSColor.yellowColor().CGColor
    self.view.addSubview(v)
}
Additionally I tried creating a custom NSWindowController and set that as the Custom Class of my main Window in the interface builder storyboard. There I have the following code:
override func windowDidLoad() {
    super.windowDidLoad()
    let f: NSRect = NSMakeRect(0, 0, 200, 200)
    let v: NSView = NSView(frame: f)
    v.layer?.backgroundColor = NSColor.yellowColor().CGColor
    self.window?.contentView?.addSubview(v)
}
This does not work either :/
I even tried setting v.wantsLayer = true as one of the answers I found online suggested, however that seemed strange from the get go and of course did nothing.
What am I doing wrong here?
Answering my own question as I exhausted all possible scenarios and of course the culprit ended up being wantsLayer.
Initially I did:
override func windowDidLoad() {
    super.windowDidLoad()
    let f: NSRect = NSMakeRect(32, 32, 200, 200)
    let v: NSView = NSView(frame: f)
    v.layer?.backgroundColor = NSColor.greenColor().CGColor
    v.wantsLayer = true
    self.window?.contentView?.addSubview(v)
    if let views = self.window?.contentView?.subviews {
        for v in views {
            print(v.frame)
        }
    }
}
I could see that the view has been added to the contentView, however it was invisible. I did a lot of things before I realised my mistake which was:
The v.wantsLayer = true declaration needed to (of course) be above the line where I specified the backgroundColor of the layer itself.
So yes... this now works:
override func windowDidLoad() {
    super.windowDidLoad()
    let f: NSRect = NSMakeRect(32, 32, 200, 200)
    let v: NSView = NSView(frame: f)
    v.wantsLayer = true
    v.layer?.backgroundColor = NSColor.greenColor().CGColor
    self.window?.contentView?.addSubview(v)
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With