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

后端 未结 1 1571
青春惊慌失措
青春惊慌失措 2020-12-24 08:57

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 pro

相关标签:
1条回答
  • 2020-12-24 09:44

    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 讨论(0)
提交回复
热议问题