ios 文本不在 UILabel 中垂直居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26649909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:25:48  来源:igfitidea点击:

Text not vertically centered in UILabel

iosswiftuilabel

提问by Loadex

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 ?

我是否必须做任何特定的事情才能使其居中?

回答by rintaro

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

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

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

默认情况下,文本与其基线对齐。你可以用baselineAdjustment属性来调整它。

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

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

valueLabel.baselineAdjustment = .alignCenters

回答by otiai10

Thanks to @rintaro, it works finally.

感谢@rintaro,它终于奏效了。

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

对于我的情况还有一件事,它不起作用,因为我正在设置ByWordWrapping. 我必须设置lineBreakModeByClipping.