Search code examples
swiftnsviewnsviewcontroller

Add custom NSViewController with Nib to view


Background info: I have an NSTableView with custom NSView cells (PreviewCell : NSView) and would like to add such a PreviewCell (with its custom nib) as subview outside of the table as well.

Project setup:

AppDelegate  [displays MasterviewController]
MasterViewController : NSViewController
MasterViewController.xib  [contains table with Preview.xib rows]

Preview : NSViewController
Preview.xib  [contains PreviewCell]
PreviewCell : NSView

The table is displayed correctly. I'm having trouble however with adding the Preview controller with Nib to the MasterViewController.

// in viewDidLoad()
var pinned = Preview(nibName: "Preview", bundle: nil)
self.view.addSubview(pinned!.view)
pinned!.view.frame = CGRect(x: 0, y: 100, width: 600.0, height: 120.0)

The view is not visible at all. If I instead add it to the contentView of the window (in AppDelegate), it works perfectly:

// in applicationDidFinishLaunching()
var pinned = Preview(nibName: "Preview", bundle: nil)
self.window.contentView.addSubview(pinned!.view)
pinned!.view.frame = CGRect(x: 0, y: 0, width: 600.0, height: 120.0)

Adding just the PreviewCell in MasterViewController (so the Nib is not used) works as well:

var pinned = PreviewCell(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.table.rowHeight))
self.view.addSubview(pinned)

What am I doing wrong here?


Solution

  • Apparently, setting an setAutoresizingMask on the subview is a bad idea. Once the autoresizing is removed, the subview (in my case Preview) was displayed correctly.