Martin Velchevski
Martin Velchevski

Reputation: 904

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

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?

Upvotes: 4

Views: 8354

Answers (1)

Martin Velchevski
Martin Velchevski

Reputation: 904

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)
}

Upvotes: 8

Related Questions