Search code examples
swiftxcodeautolayout

Which view to expand when adding constraint between two views


I'm taking the cs193p online course to learn ios development. Yet I'm confronted with a problem when I tried to add spacing constraint between two stack views. (The one with blue buttons(view1) and the one with labels(view2) )

storyboard

I want the view1 to expand while keeping view2 unmodified. But it turned out that view2 always expand, even if I set the content hugging priority of view 2 higher than that of view1. How could I solve this problem?


Solution

  • Unless you've given your labels an explicit width, their width will be set by their intrinsic content size. The hugging priority for the labels is low, so the labels are free to grow to fill their container. So, the containing stack view will always be hugging its content since the labels can grow. You need to restrict the growth of the labels' widths in order for the hugging priority of the stack view to have any effect.

    The solution is to either give your labels an explicit width constraint, or even easier to set their hugging priorities to be high as well. This will keep the labels from growing and will allow the stack view to hug the label's minimum size. Finally, Auto Layout will choose to expand view1 instead.