[英]Text not vertically centered in UILabel
I've created a Label with the following code : 我用以下代码创建了一个Label:
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 ? 我是否必须做任何特定的事情才能使它居中?
The problem is that font size is shrunk by adjustsFontSizeToFitWidth = true
, but it does not adjust the lineHeight
automatically. 问题是
adjustsFontSizeToFitWidth = true
会缩小字体大小,但它不会自动调整lineHeight
。 It remains to be for original font size that is 50
. 它仍然是
50
原始字体大小。
By default, the text is aligned to its baseline. 默认情况下,文本与其基线对齐。 you can adjust it with
baselineAdjustment
property. 您可以使用
baselineAdjustment
属性进行调整。
In your case, you should set it to UIBaselineAdjustment.alignCenters
. 在您的情况下,您应将其设置为
UIBaselineAdjustment.alignCenters
。
valueLabel.baselineAdjustment = .alignCenters
Thanks to @rintaro, it works finally. 感谢@rintaro,它终于有效了。
One more thing for my case, it didn't work because I was setting ByWordWrapping
. 对我的情况还有一件事,它没有用,因为我正在设置
ByWordWrapping
。 I had to set lineBreakMode
as ByClipping
. 我必须将
lineBreakMode
设置为ByClipping
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.