How to programatically add views to NSWindow (or NSView)?

Viewed 7461

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?

1 Answers
Related