如何在UITextView中获取一行的高度

19

enter image description here

如上图所示,lineHeight是橙色框的高度。如何获取蓝色框(即lineHeight+行间距)的高度?谢谢!

更新:我发现lineHeight的行为取决于内容中的字符。如果内容全部是英文,则lineHeight是正确的(例如,在默认的UITextView中为21)。但是,如果内容混合了中文字符,则UIFont lineHeight仍然报告为21,而self.textView.contentSize.height会有不同程度的增加:

English - adding 21 points for each line
Chinese - adding 24 points for each line

更新 (sizeWithFont:)

CGSize constrainedRect = CGSizeMake(1000, 1000);
CGSize rectEnglish = [@"hello\nworld" sizeWithFont:self.textView.font constrainedToSize:constrainedRect lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"width: %.2f height: %.2f", rectEnglish.width, rectEnglish.height);
CGSize rectChinese = [@"你\n好嗎" sizeWithFont:self.textView.font constrainedToSize:constrainedRect lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"width: %.2f height: %.2f", rectChinese.width, rectChinese.height);

输出:

width: 41.00 height: 42.00
width: 34.00 height: 42.00
2个回答

21

你需要使用


yourTextView.font.lineHeight

1
请注意,UIFont.lineHeight 仅适用于 iOS4.0 及以上版本。 - Nick Forge

1

尝试使用{{link1:NSString UIKit 添加}}。一些-sizeWithFont:的变体应该是你所需要的。


在我看来,-sizeWithFont 似乎也忽略了语言问题(请参见有关问题的 -sizeWithFont 的更新)。 - ohho
你不能直接使用将要绘制的文本吗? - Jeff Kelley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接