1
votes

Example 1Example 2

In the above, the orange, blue and green views are subviews of the yellow view. I need the parent (yellow) view's borders to hug its subviews. The only movement that's occurred between the two images is the green subview moving up and to the right.

Because the bottom of the orange view is now lower than the bottom of the green view, the parent view hugs the orange view's bottom edge.

Similarly, because the green view's right edge is past the blue view's right edge, the parent view hugs the green view's right edge.

Is there a way to do this with Auto Layout constraints, or would I have to write custom code?

1

1 Answers

2
votes

For the bottom edge, both the orange and green views require two vertical space constraints each. They are:

  • Vertical space constraint with relation set to "Greater Than or Equal" and constant set to 0.
  • Vertical space constraint with relation set to "Equal", constant set to 0 and a priority lower than the first constraint.

The first constraint ensures that no matter what, the space will be greater than or equal to zero. The second constraint says if possible, also have the space equal to exactly zero.

The above can then be replicated for the right edges of the blue and green views, using horizontal space constraints instead.