UILabel adds unnecessary top and bottom padding when growing vertically and breaking lines
Asked Answered
C

3

12

Let's say we have a UILabel, that is pinned from all sides to its superview. Number of Lines is set to 0 (so we can display multiline strings) and we use Truncate Tails strategy for line breaks.

If we have a single, short line of text, which does not break lines, the label's inside padding/inset looks fine:

Single line of text

When using multiline text, that will force the label to start breaking lines, ellipsis appear at the end of the label, but artificial padding/inset is added to top/bottom of the label as well. The label is inflated vertically, even though it is still displaying only 1 line of text:

Multiline text

Constraints:

Constraints

Line breaks:

Line breaks

What I tried already

Changed Content Hugging Priority to 1000 for both Horizontal and Vertical axis, so the UILabel doesn't grow more than required, but that does not solve the issue.

Switching between different Line Breaks strategies (Clip, Character Wrap, Truncate, ...) does not solve the issue either.

I am able to reproduce this behavior in both Xcode 6 and Xcode 7 beta, Interface Builder and while running the app.

Conidium answered 7/8, 2015 at 12:51 Comment(5)
Did you try to call [YourLabel sizeToFit]?Romansh
@Walucas: Yes I tried that, but with no success. This issue presents itself both in Interface Builder and running application.Conidium
Did you tried to set preferredMaxLayoutWidth in code? You can set it to self.frame.size.width - 2*8 which fits your margins.Pawsner
@CandostDagdeviren thanks, but no luck eitherConidium
Did you changed the frame of your view? Because your bottom space constraint should be grater than 20 and it prevents your UILabel's getting bigger in vertical.Pawsner
C
3

Looks like the only way to fix the unintentional padding is to set Lines to a constant (eg. 3). The UILabel will still grow dynamically and will refrain from adding any padding.

Conidium answered 10/8, 2015 at 12:45 Comment(0)
X
0

Unchecking the 'explicit' checkbox in Interface builder for the Desired width of the label solved this for me.

Xanthate answered 22/7, 2021 at 12:0 Comment(0)
P
-1

I got the same problem when see it in interface builder. But if i just run it the final result in simulator works without any padding. The key is you have to set the backgroundColor property of the label.

Pockmark answered 29/8, 2017 at 3:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.