简体   繁体   中英

UIStackView with “wrap content” width

Problem: Create horizontal UIStackView with 2 elements 在此处输入图片说明

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)?

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

在此处输入图片说明

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

在此处输入图片说明

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

在此处输入图片说明

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

在此处输入图片说明

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 UILabel s 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:

在此处输入图片说明

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

在此处输入图片说明 Thats all :) Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM