ios - 如何使用 Text Kit 查找单行文本的高度

标签 ios textkit

我正在尝试使用 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 method defaultLineHeightForFont: 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/

相关文章:

ios - 使用 AddressBook 框架时,iOS 11 上的应用程序崩溃?

ios - 嵌入在 UITextView 中的三列表

ios - 在 iOS 7 中,当 adjustsFontSizeToFitWidth 为 YES 时,如何从 UILabel 获取调整后的字体大小?

iphone - 我可以在我的程序中使用 Siri 吗?

ios - 向tableview添加渐变层

objective-c - LLVM GCC 4.2 EXC_BAD_ACCESS

ios - fontDescriptorWithSymbolicTraits ios 8 错误的快速替代方案

ios - 字符串中的内联按钮和/或文本字段,使用 Swift 包装与文本相同的文本

iOS UITextView 无序/有序列表,如 Notes App

ios - 如何在 swift3 的 UILabel 中获取 JSON 数据