我正在尝试使用 Text Kit 查找单行文本的高度。 Calculating Text Height documentation说
Note: You don’t need to use this technique to find the height of a single line of text. The
NSLayoutManager
methoddefaultLineHeightForFont:
returns that value. The default line height is the sum of a font’s tallest ascender, plus the absolute value of its deepest descender, plus its leading.
但是,当我检查 NSLayoutManager Class Reference (也在 Xcode 中进行测试)我没有看到 defaultLineHeightForFont:
方法。这是为什么?有替代方案吗?
注意事项:
- 我不想set the line height .
- 有ways to do this显然不使用 Text Kit。但是,由于我已经设置了 Text Kit 堆栈并且文档似乎表明这是可能的,所以我想使用 Text Kit。
- 我更喜欢 Swift 答案,但 Objective-C 也可以。
更新
在阅读@JoshCaswell 的评论之前,我没有意识到我链接到的文档是针对 OS X 的。我正在专门寻找如何在 iOS 中执行此操作。
最佳答案
在 TextKit 中,您可以使用布局管理器获取行高,方法是
- lineFragmentRectForGlyphAtIndex:effectiveRange:
.正如您从该函数的名称中注意到的那样,它被命名为“行片段”。为什么?因为您的布局并不总是有一条完整的线,而是您可能有一个排除路径(包含形状或图像),其中文本环绕在它周围。在这种情况下,您有一部分行(行片段)用于放置文本。
在布局管理器的委托(delegate)中,您将实现一个如下所示的函数:
-(void)layoutManager:(NSLayoutManager *)layoutManager didCompleteLayoutForTextContainer:(NSTextContainer *)textContainer atEnd:(BOOL)layoutFinishedFlag{
//This is only for first Glyph
CGRect lineFragmentRect = [layoutManager lineFragmentUsedRectForGlyphAtIndex:0 effectiveRange:nil];
// The height of this rect is the line height.
}
关于ios - 如何使用 Text Kit 查找单行文本的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35076815/