Search code examples
iosswiftautolayout

Autolayout two views vertically with dynamic height aligned top


I have two views that can be dynamic height. Dependent on content either view1 or view2 is the highest.

The highest view should determinate the distance to view3.

In my current implementation view1 and view2 each have a constraint for x pixels for view3. But the problem is view1 and view2 then always will be same height (all the content will not align top)


Solution

  • Try this. Make sure both views 1 and 2, have some constraint to the top of the superview and to the sides (or fixed width, whatever it takes to fix the views in the horizontal direction). Lets say you want that distance to the bottom view to be 30. Give view 1 a constraint to view 3 of =30 with a priority of 200, and another one of >=30 with a priority of 1000 (default). View 2 should just need one constraint to view 3 of >=30 with 1000 priority.

    The low priority constraint (of 200) will fix the position of view 3 initially, but is low enough that if view 2 expands, view 3 will move down, and also low enough that the default Content Hugging Priority of view 1 will keep it from expanding its height if it doesn't need to based on its text size.