Text not vertically centered in UILabel

人走茶凉 提交于 2020-05-24 09:36:28

问题


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 ?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/26649909/text-not-vertically-centered-in-uilabel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!