简体   繁体   中英

Auto-layout XIB embedded in programmatic UIView not sizing to parent

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):

屏幕截图 1

After rotating to portrait:

屏幕截图 2

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.

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM