Inserting an NSView (Cocoa) in NSWindowController Views hierarchy

I have an NSWindowController with several IBOutlets created in storyboard.

I want to add an NSView and fill it with some color. I need to place it at a specific position in views hierarchy.

I have tried 2 ways, no one succeeds.

First.

  • include a custom view in storyboard
  • connect to an IBOutlet
  • in an init of controller, set the layer for the view
  • Result: crash

Second

  • build programmatically
  • Result: I do not find where to put this code in the controller code

That's basic Cocoa, but way more painful than iOS.

Answered by Frameworks Engineer in 874391022

For your first approach, are you able to provide information about the crash, like a crash log?

For your second approach, it is common to see initial view hierarchy setup for a window in your window controller subclass’s overridden windowDidLoad method.

For a view that just needs to display a solid color, NSBox can be used for this purpose:

let box = NSBox()
box.boxType = .custom
box.borderWidth = 0.0
box.fillColor = NSColor.systemRed
Accepted Answer

For your first approach, are you able to provide information about the crash, like a crash log?

For your second approach, it is common to see initial view hierarchy setup for a window in your window controller subclass’s overridden windowDidLoad method.

For a view that just needs to display a solid color, NSBox can be used for this purpose:

let box = NSBox()
box.boxType = .custom
box.borderWidth = 0.0
box.fillColor = NSColor.systemRed

The error in case 1: implicitly unwrapping an Optional value.

Second option works like a charm. And allows to add subviews in the box, easily.

When it comes to anything related to nibs or storyboards, init is playing with fire. In fact, the entire setup sequence is quite delicate and depends on your point of view.

For example, if you're starting with a standard NSViewController, you don't touch any @IBOutlet until viewDidLoad(). But even there, there's not much you can do with those objects beyond basic setup. There's no geometry or windows at that point. For that, you have to wait until "viewWillAppear" or "viewDidAppear". Then you'll have a window and know its size. But if you're using Auto Layout, you don't know the sizes of any views until after Auto Layout has settled down, whenever that happens. Hopefully you've done your layout properly and it's a finite process.

From an NSWindowController perspective, I have no idea. That class is required for certain very specific operations, but not what you're talking about. That's why one class is a "Window" controller and the other is a "View" controller.

Inserting an NSView (Cocoa) in NSWindowController Views hierarchy
 
 
Q