user9168699
user9168699

Reputation: 103

Labels inside of horizontal stack view are of equal width?

I have a stack view with these properties: Axis: Vertical Alignment: Fill Distribution: Fill

I add other horizontal stack views to that vertical one with the below properties: Axis: Horizontal Alignment: FirstBaseline Distribution: Fill

Each one of those horizontal stack views contain two labels. I want the labels to shrink/expand their widths according to the text inside of them. Whenever I set their numberOfLines to 0, both labels have equal widths, and the increase happens in the height, If I set numberOfLines to 1, they expand/shrink their widths according to the text, but if the text requires more than one line, the rest of the text doesn't appear. Any help is much appreciated.

Upvotes: 6

Views: 9889

Answers (4)

AppleDeveloper
AppleDeveloper

Reputation: 1443

I faced similar problem , I set below properties for both the UILabels and it worked for me

label1.setContentHuggingPriority(.required, for: .horizontal)
label1.setContentCompressionResistancePriority(.required, for: .horizontal)

label2.setContentHuggingPriority(.required, for: .horizontal)
label2.setContentCompressionResistancePriority(.required, for: .horizontal)

When Priority is set to .required ,it prevents any shrinking as there should be nothing more important.

Upvotes: 0

LeiLou65
LeiLou65

Reputation: 51

I had a similar issue, two labels inside horizontal stackview. label1 with numberOfLines = 1 and label2 was multiline. (numberOfLines = 0) both labels were having equal width even if label 2 had a much longer text!

To fix this issue I had to set a width constraint(based on its current content) for label1 with priority = 750 (high but not required).
This way if the label has a long text and its width grows bigger than that constraint then label width = its content size.
if label width is smaller than the constraint then label width = constraint.

See screen shot

Upvotes: 5

MichaelV
MichaelV

Reputation: 1261

Autolayout yet struggling to determine width of label inside StackView, when number of lines is 0. My workaround is to set preferred width.

Upvotes: 1

Guy Kogus
Guy Kogus

Reputation: 7351

If you have 2 labels, with number of lines set to 1, next to each other, trying to fit in a stack view of 200 pixels, but each label needs 150 pixels, you have to solve the problem:

Which label is compressed and which gets its full width?

This depends on their compression resistance priorities. Auto-layout won't compress both of them equally by default, you'd need to set their constraints to have equal width).

It looks like UIStackView struggles to get the layout constraints of the label if you set the number of lines to 0. If their text is of different lengths then it seems to lose all sense of itself. In this case I'd suggest to set the widths of the 2 labels to be equal, unless that doesn't work for you.

Upvotes: 3

Related Questions