13
votes

I have a xib file representing a simple view with auto-layout that I am instantiating with [[NSBundle mainBundle] loadNibNamed:@"name"][0] and adding to a programmatically-created UIView via addSubview:.

The problem is that the view is not stretching to meet the size of the view it is embedded in; rather it appears to be defaulting to the size that was specified in the xib file. (I also can't find any way to set constraints on the container view itself in the xib file, only its subviews.)

Also somewhat strangely, when I rotate the iPad, the view's width further shrinks proportionately. So it's clearly wired up somehow, but with the wrong initial values.

What connection am I missing to get this embedded view to fit the view hierarchy properly?

Screenshots (magenta colouring added for debugging):

screenshot 1

After rotating to portrait:

screenshot 2

2

2 Answers

18
votes

The reason it doesn't resize itself to fill its new superview is that you haven't arranged for it to do that. In short, you need to add constraints, in code, to relate the two views after adding one to the other.

Most likely, IB set the view to translate its autoresizing mask to constraints. What its autoresizing mask is can be hard to determine from the NIB when it's set to use auto layout.

Anyway, when you add it to the superview, the automatically generated constraints maintain its current frame. When the superview resizes, they resize it according to the autoresizing mask (probably allowing width and height to vary but not the distance to the superview edges).

When you're using auto layout, you should do the following:

  • Either turn off translatesAutoresizingMaskIntoConstraints in the NIB or turn it off in the code which adds it to the superview. Which of those approaches you take depends on whether you anticipate that the view will ever be added as a subview of a framework view class that manages the layout of its subviews. If you might, then you should leave it on in the NIB and let that class decide whether to turn it off.

  • After adding the view to its superview, add constraints to the superview which controls where the view should be laid out.

0
votes

What helped me is setting container’s ‘layout’ to Autoresizing Mask:

enter image description here