UILabel shrinks when text changes

I have a view containing a container (gray) that contains a UILabel (blue).

enter image description here

I have layout restrictions, so the View container is always 8 pixels larger than the label on each side, and the borders of the left / top / right container are fixed. The view of the container is stretched accordingly when the orientation of the device changes.

The labelOfLines value is 0. I set the label text in the code. The height of the label increases to fit the text as expected.

Here's the problem: when I rotate the device to landscape, the width of the shortcut increases to fit the width of the screen, and the text fits on 2 lines. But UILabel does not compress its height to fit snugly against the text. Pay attention to the extra space above and below the text on the label.

enter image description here

So, how can I reduce the height of the shortcut when the device is rotated to fit snugly on the text?

I tried calling [myLabel sizeToFit] in the viewWill/DidLayoutSubviews , but this did not have a visible effect.

+4
source share
2 answers

Check if the label has a fixed height constraint: NSLog(@"%@", label.constraints);

0
source

Step 1. Subclass of UILabel.

Step 2: set your own label class in a subclass of labels.

Step 3: Override -layoutSubviews in your custom class.

Step 4: In the overridden method, call [self sizeToFit];

It worked for me.

0
source

All Articles