4

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?

Martin Velchevski
  • 874
  • 11
  • 33
  • you need to set `v.wantsLayer = true` – Leo Dabus Mar 26 '16 at 19:27
  • I tried `v.wantsLayer = true` in both method calls `viewDidLoad()` and `windowDidLoad()` once again, however both views are still not visible. I even tried crazy things like setting the contentView's layer color to `clearColor`, thinking that maybe all views are added below it. I even went so far as to do `self.window?.contentView?.addSubview(v, positioned: NSWindowOrderingMode.Above, relativeTo: self.window?.contentView)`... Still no cigar. Views are nowhere to be seen. – Martin Velchevski Mar 26 '16 at 20:19

1 Answers1

7

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)
}
Martin Velchevski
  • 874
  • 11
  • 33