如何从NSString计算文本矩形的高度? [英] How to calculate the height of the text rectangle from an NSString?

查看:217
本文介绍了如何从NSString计算文本矩形的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有这个:

sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:

但是由于CGSize总是具有相同的高度,不能调整为任何缩小的文本或任何其他,CGSize不会告诉

But since the CGSize always has the same height and doesn't adjust to any shrinked text or whatsoever, the CGSize is not telling how heigh the text is.

示例:使用320 x 55点制作一个UILabel,并在其中放置一个loooooooooooooong的文本。让标签缩小文本。惊喜:CGSize.height仍保持相同的高度,即使文本太小,你需要一个显微镜。

Example: Make a UILabel with 320 x 55 points and put a loooooooooooooong text in there. Let the label shrink the text down. Surprise: CGSize.height remains the same height even if the text is so tiny that you need a microscope.

确定,所以后,我的脑袋对我的macbook pro是一半方式坏了现在,唯一认为可以帮助的是讨厌的actualFontSize。但是字体大小是在pica我想,这不是真的你在屏幕上得到,不是吗?

Ok so after banging my head against my macbook pro which is half way broken now, the only think that can help is that nasty actualFontSize. But the font size is in pica I think, it's not really what you get on the screen, isn't it?

当字体大小是10,是我的文本真的10点最高?有一段时间,我尝试了一下,一旦文本有一个或一些字符延伸到下面(像y的尾巴),它是超出边界,整个文本大于10点。

When that font size is 10, is my text really 10 points heigh at maximum? Once in a while I tried exactly that, and as soon as the text had a y or some character that extends to below (like that tail of an y does), it is out of bounds and the whole text is bigger than 10 points.

那么,如何计算单行uilabel的真实文本高度,而不需要长胡子和一些医院体验?

So how would you calculate the real text height for a single line uilabel without getting a long beard and some hospital experience?

推荐答案

听起来像是从该函数调用获得实际的字体大小后,您需要再次调用该新大小:

Sounds like after you get the actual font size from that function call, you need to call again with that new size:

NSString* yourString = @"SomeString";
float actualSize;
[yourString sizeWithFont:yourFont 
             minFontSize:minSize 
          actualFontSize:&actualSize 
                forWidth:rectWidth 
           lineBreakMode:breakMode];

CGSize size = [yourString sizeWithFont:[UIFont fontWithName:fontName size:actualSize]];

这篇关于如何从NSString计算文本矩形的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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