文字未在UILabel中垂直居中 [英] Text not vertically centered in UILabel

查看:446
本文介绍了文字未在UILabel中垂直居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用以下代码创建了一个标签:

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 :

我是否需要做任何特定的事情才能使它居中?

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

推荐答案

问题是adjustsFontSizeToFitWidth = true缩小了字体大小,但它不会自动调整lineHeight.仍然是50的原始字体大小.

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.

默认情况下,文本与基线对齐.您可以使用 baselineAdjustment 属性.

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

在您的情况下,应将其设置为UIBaselineAdjustment.alignCenters.

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

valueLabel.baselineAdjustment = .alignCenters

这篇关于文字未在UILabel中垂直居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆