2

Problem: Create horizontal UIStackView with 2 elements enter image description here

Item width with "Short text 2" should be "wrap content". Item with "Long text 1" should fill all free space.

Please help to understand, how it can be created in code (Swift language)?

ricardopereira
  • 11,118
  • 5
  • 63
  • 81
Natali
  • 2,934
  • 4
  • 39
  • 53
  • 2
    iOS SDK doesn't have definitions for 'item weight' or 'wrap content'. Your question is very confusing. – Desdenova Oct 22 '18 at 08:54
  • You can refer to this --- https://stackoverflow.com/questions/41436716/how-to-increase-width-of-textfield-according-to-typed-text – Shubham Bakshi Oct 22 '18 at 08:55

1 Answers1

5

Step 1: Drag a StackView add left, right, top/bottom constraint to it. (ignore error for now)

enter image description here

Step 2: Drag two labels and add it to stackView (continue to ignore warning)

enter image description here

Step 3: Now you need to resolve horizontal content ambiguity so change the content hugging priority of left label to 250 while leaving the right labels content hugging priority at 251

enter image description here

Step 4: Now comes your question of warp content for vertical height :) Simply select the right label and set its content compression resistance to 999 while leaving left label's content compression resistance at 751

enter image description here

If you are wondering whats happening with content compression resistance and content hugging priority and all, please read apple docs on the same for more detail

Just to give a gist of what am doing, in iOS UILabels have implicit content size, so they take size based on content. So is Stack View. Now because StackView has to deduce its height based on two labels it has and both of them have same content compression resistance and end up having different height in order to resolve confusion it looks for further assistance from you. You do that specifying that right label resists more to change in its implicit vertical height compared to left label.

That means now stack view knows that it has to consider right labels height to adjust its height while it can override the implicit size of left label :)

Confirmation of logic:

enter image description here

On changing right label font stack view height automatically increased and increased the height of left label as well :)

EDIT on Comment by OP:

As OP suggested in comment that conern is width and not height, step 4 is not necessary, your problem is resolved at the end of step 3. On setting content hugging priority it self

on changing right labels content UI updates as shown below

enter image description here Thats all :) Hope that helps

Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78