这与其他所有“我如何将文本置于 UILabel
中的中心”有点不同......
我有一个带有一些文本的 UILabel
,我希望将文本垂直居中于 UILabel
. 什么's the big deal, right? That'是默认值 . 问题来了,因为我的文字是动态的,我打开了自动收缩 . 随着文本变大,字体大小缩小 . 你得到这种行为 .
请注意,字体基线没有移动,我希望它移动,所以数字在 UILabel's
框架中垂直居中 .
容易,对吗?我只记得框架的原始中心 viewDidLoad
self.workoutTimeCenter = _workoutTimeLabel.center;
然后我在更改文本后调用 sizeToFit
,对吧?
[_workoutTimeLabel sizeToFit];
_workoutTimeLabel.center = _workoutTimeCenter;
好吧, sizeToFit
确实,我想,它确实应该做什么,调整框架的大小,使文字适合而不缩小!
如何在尊重基线和自动收缩的同时将文本垂直居中于 UILabel
? (注意, iOS5 和之后的解决方案很好,我甚至可以处理 iOS6 及更高版本的解决方案 . )
5 回答
根据我的经验,您可以将
-[UILabel baselineAdjustment]
属性设置为UIBaselineAdjustmentAlignCenters
以实现您所描述的效果 .来自docs:
和
EDIT: adding a full view-controller that demonstrates this:
How to Use: Call this method after setting the text to your label.
Note: I ahev taken UILabel from xib. You can take it programmatically too in that case you will have to set its text alignment NSTextAlignMentCenter
在IB中工作时,请务必将对齐基线设置为居中
Note: line break CANNOT be word wrap for this to work, so it will NOT work multiline (good to set the line break to Truncate tail)
尝试实现此逻辑:
它给了我很多帮助 . 希望它适合你 .
尝试