Search code examples
iosautolayout

iOS autolayout, how to make View wraps content?


View heirachy:

- RootView
  - ContainerView
    - Label1
    - Label2

I want ContainerView always wraps Label1 and Label2,adjust height of ContainerView when Label1 or Label2 contents change.

My constraints:

H: [Label1]-[Label2(==Label1)]
V: [Label1]-(>=0)
V: [Label2]-(>=0)

No exception but got ambiguous layout.


Solution

  • Please follow the logic below. It should get you through your problem:

    1. The first thing you need to do is make your Labels wrap their content. You can follow Mark's suggestion to do this here

    2. Save a reference to the height constraint of your ContainerView from your Storyboard or .xib file

    3. Update the height constraint with an appropriate height every time after you update the content of the two labels

    This worked for me in a similar situation. You also have to add all the constraints up down left right for the ContainerView to fit in the RootView