swiftcocoainterface-buildernsstackview

Programmatically adding InterfaceBuilder-created views to an NSStackView squashes them to 0 height


I've been trying to add a custom view I've created in Interface Builder to an NSStackView, but am failing miserably.

This is my view controller. It currently does nothing but initialize the view from the NIB:

class ServiceControlViewController : NSViewController {
    init() {
        super.init(nibName: "ServiceControlView", bundle: nil)!
    }
}

And here's how I'm trying to add the newly created view to the stack view (this happens in the app delegate):

@IBOutlet weak var stackView: NSStackView!

@IBAction func addButtonClicked(sender: AnyObject) {
    let viewController = ServiceControlViewController()
    stackView.addView(viewController.view, in: .top)
    stackView.layoutSubtreeIfNeeded()
}

When I print the frame of the created view before it is added to the stack view it has the correct size. If I print it after, it is squashed to zero height. I suspect there is some auto-resizing magic going on that I don't understand, but I haven't been able to fix it.

Interestingly enough, if I set the ServiceControlViewController's view to e.g. be an NSButton, then it is correctly added and not squashed to zero height. It only happens with the Custom Views I create.

PS: My InterfaceBuilder-created view simply contains a bunch of buttons and a label:

enter image description here

PPS: I've added an MWE


Solution

  • It seems like there are no constraints on that custom view to make it larger than zero size. You'll have to determine what its sizing behavior is, e.g. is it always the same size, or resizable with a minimum, etc.

    And then in IB you can build the constraints necessary to create that effect. e.g.: sample constraints

    Alternatively, you could put these controls into a stack view to get a similar result.