How do you make Interface Builder respect a custom view's intrinsic content size in constraint based layout?

bitmusher picture bitmusher · Dec 5, 2012 · Viewed 8.5k times · Source

Interface Builder in XCode 4.5 respects the intrinsicContentSize for some views, e.g. NSButton, but I can't convince it to respect it on my own custom subviews. This causes IB to add extra constraints trying to force the layout drawn in IB, which then causes the intrinsic sizes to not be used when the program is run.

For example, consider a button centered in a window, and a custom view centered in a window…

IB constraints for centered NSButton

IB constraints for centered NSView

You can see that the custom view gets four constraints, presumably because IB doesn't know the view's intrinsicContentSize. You can change which extra constraints are added, e.g. you can force it to be width and height instead, but you can't delete them.

I'm coping with this now by searching and deleting the extra constraints in my awakeFromNib, but there must be a better way to do this.

Answer

ravron picture ravron · Aug 29, 2014

Set a placeholder intrinsic content size — a "guess," if you will — in Interface Builder.

  1. Select your custom view.
  2. Show the size inspector (Shift5).
  3. Change the "Intrinsic Size" drop-down from "Default (System Defined)" to "Placeholder."
  4. Enter reasonable guesses at your view's runtime width and height.

These constraints are removed at compile-time, meaning they will have no effect on your running app, and the layout engine will add constraints as appropriate at runtime to respect your view's intrinsicContentSize.