当 -adjustsFontSizeToFitWidth 设置为 YES 时,如何计算 UILabel 的字体大小?
当myLabel.adjustsFontSizeToFitWidth = YES
时,UILabel将自动调整字体大小,以防文本对于标签来说太长。例如,如果我的标签只有 100px 宽,并且我的文本太长,无法适应当前的字体大小,它会缩小字体大小,直到文本适合标签。
当字体大小缩小时,我需要从 UILabel 获取实际显示的字体大小。例如,假设我的字体大小实际上是 20,但 UILabel 必须将其缩小到 10。当我向 UILabel 询问字体和字体大小时,我得到的是旧字体大小 (20),但不是显示的字体大小(10)。
When myLabel.adjustsFontSizeToFitWidth = YES
, UILabel will adjust the font size automatically in case the text is too long for the label. For example, if my label is just 100px wide, and my text is too long to fit with the current font size, it will shrink down the font size until the text fits into the label.
I need to get the actual displayed font size from UILabel when the font size got shrunk down. For example, let's say my font size was actually 20, but UILabel had to shrink it down to 10. When I ask UILabel for the font and the font size, I get my old font size (20), but not the one that's displayed (10).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不确定这是否完全准确,但希望它应该非常接近。它可能不会考虑截断的字符串或标签的高度,但您可以手动执行此操作。
该方法
- (CGSize)sizeWithFont:(UIFont *)font minFontSize:(CGFloat)minFontSizeactualFontSize:(CGFloat *)actualFontSize forWidth:(CGFloat)宽度 lineBreakMode:(UILineBreakMode)lineBreakMode
将返回文本大小,并注意它还有一个实际使用的字体大小的参考参数。
I'm not sure if this is entirely accurate, but it should be pretty close, hopefully. It may not take truncated strings into account, or the height of the label, but that's something you might be able to do manually.
The method
- (CGSize)sizeWithFont:(UIFont *)font minFontSize:(CGFloat)minFontSize actualFontSize:(CGFloat *)actualFontSize forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode
will return the text size, and notice that it also has a reference parameter for the actual font size used.
万一有人仍然需要答案。
在 iOS9 中,您可以使用
boundingRectWithSize:options:context:
来计算实际字体大小。请注意,context.minimumScaleFactor 不应为 0.0 才能进行缩放。In case anybody still needs the answer.
In iOS9 you can use
boundingRectWithSize:options:context:
to calculate actual font size. Note that context.minimumScaleFactor should not be 0.0 for scaling to work.对于单行 UILabel,这个简单的解决方案可以很好地工作:
For one-line UILabel works fine this simple solution:
Swift 5
对于单行 UILabel
获取实际字体大小非常简单:
Swift 5
For one-line UILabel
Getting the actual font size is then as simple as:
我的代码工作得很好,部分来自@Igor
my code works great, part from @Igor