1

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
fresskoma
  • 25,481
  • 10
  • 85
  • 128

2 Answers2

1

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.

Taylor
  • 3,183
  • 17
  • 18
1

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.

Correct. This is because an NSButton has something your custom NSViews do not have: an intrinsicContentSize. This is what the stack view uses to size and position your added views.

So, override intrinsicContentSize in your custom views and all will be well.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Since both your answers helped me equally, I accepted @taylors since he has less reputation. Your answer is much appreciated, though :) – fresskoma Sep 27 '16 at 12:05