Text not vertically centered in UILabel

IosSwiftUilabel

Ios Problem Overview


I've created a Label with the following code :

func setupValueLabel() {
    valueLabel.numberOfLines = 1
    valueLabel.font = UIFont(name: "Avenir-Black", size: 50)
    valueLabel.adjustsFontSizeToFitWidth = true
    valueLabel.clipsToBounds = true
    valueLabel.backgroundColor = UIColor.greenColor()
    valueLabel.textColor = valuesColor
    valueLabel.textAlignment = NSTextAlignment.Center
}

I don't really understand why but the label is not vertically centered : Label not centered

Do I have to do anything specific so it can be centered ?

Ios Solutions


Solution 1 - Ios

The problem is that font size is shrunk by adjustsFontSizeToFitWidth = true, but it does not adjust the lineHeight automatically. It remains to be for original font size that is 50.

By default, the text is aligned to its baseline. you can adjust it with baselineAdjustment property.

In your case, you should set it to UIBaselineAdjustment.alignCenters.

valueLabel.baselineAdjustment = .alignCenters

Solution 2 - Ios

Thanks to @rintaro, it works finally.

One more thing for my case, it didn't work because I was setting ByWordWrapping. I had to set lineBreakMode as ByClipping.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLoadexView Question on Stackoverflow
Solution 1 - IosrintaroView Answer on Stackoverflow
Solution 2 - Iosotiai10View Answer on Stackoverflow