Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bottom of UILabel text cut off when using adjustsFontSizeToFitWidth

When the font size of my UILabel gets adjusted to fit the width of the label, the bottom of the text gets cut off. Here's a screenshot of the debug view:

enter image description here

The UILabel has the following characteristics:

  • System font (semibold, 36pt)
  • numberOfLines = 1
  • baselineAdjustment = .alignCenters
  • translatesAutoresizingMaskIntoConstraints = false
  • auto-layout constraints: top, left and right pinned are pinned, and there is no bottom or height constraint
  • adjustsFontSizeToFitWidth = true, minimumScaleFactor = 0.1
  • No text by default, the text is given after initialization
  • lineBreakMode = .byWordWrapping

Additional elements:

  • This only happens when the font size does get reduced. If the text is shorter and fits at the original font size, it's not cut off.
  • If I manually change the font size so that the text fits, it does not get cut off. It only happens when it automatically adjusts to that font size.

Things that did not work:

  • Use .attributedText rather than .text property
  • Call sizeToFits, setNeedsLayout()/layoutIfNeeded()
  • Setting a long text by default to the label
  • Trying all settings of baselineAdjustment ( setting to .none worked, see answer)

(As I was typing this question, I tried changing baselineAdjustment settings again to confirm it didn't work and this time, it worked. See answer.)

like image 360
Kqtr Avatar asked Jan 29 '23 06:01

Kqtr


1 Answers

While I was typing out the answer and going back on every setting I had tried, setting the label's baselineAdjustement to .none fixed the issue.

label.baselineAdjustment = .none

FYI, the following documentations extracts were confusing to me:

From the documentation of UILabel baselineAdjustement:

The default value of this property is alignBaselines.

From the documentation of UIBaselineAdjustment:

.none: This is the default adjustment.

I'd be interested if anyone could confirm in the comments, but from my experiments, .none doesn't seem to be the default baselineAdjustment of UILabel. I had to specifically set the baselineAdjustment to .none to fix the bug mentioned in the question.

like image 130
Kqtr Avatar answered Feb 01 '23 05:02

Kqtr