1

I'm trying to find the height of a single line of text using Text Kit. The Calculating Text Height documentation says

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.

However, when I checked the NSLayoutManager Class Reference (and also testing in Xcode) I didn't see a defaultLineHeightForFont: method. Why is that? Is there an alternative?

Notes:

  • I'm not trying to set the line height.
  • There are ways to do this apparently that do not use Text Kit. However, since I already have my Text Kit stack set up and the documentation seems to indicate that it is possible, I would like to use Text Kit.
  • I prefer Swift answers but Objective-C is ok, too.

Update

I did not realize that the documentation I linked to was for OS X until I read @JoshCaswell's comment. I am specifically looking for how to do this in iOS.

Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • You linked to an OS X programming guide, the tvOS copy of the `NSLayoutManager` reference, and tagged the question with iOS. Can you clarify which platform you're targeting? On OS X, [`NSLayoutManager` does indeed have `-defaultLineHeightForFont:`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSLayoutManager_Class/#//apple_ref/occ/instm/NSLayoutManager/defaultLineHeightForFont:) – jscs Jan 29 '16 at 05:55
  • Ah, I missed that. I am targeting iOS, not OS X. – Suragch Jan 29 '16 at 06:05
  • I _really_ hate Apple's latest doc search web interface. It's super easy to confuse oneself in that way, hitting the tvOS doc for something when you're looking for OS X (and the keyword results for simple class names are atrocious). – jscs Jan 29 '16 at 19:11

1 Answers1

3

In TextKit, you can use the layout manager to get the line height using - lineFragmentRectForGlyphAtIndex:effectiveRange:. As you notice from the name of this function, it is named "line fragment". Why? Because it is not always the case that your layout has a complete line, but instead you might have an exclusion path (that contains a shape or image) where the text is wrapped around it. In this case you have part of the line (line fragment) where your text is laid out.

In the delegate of the layout manager, you would implement a function that might look as follows:

-(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.
}
jscs
  • 63,694
  • 13
  • 151
  • 195
Wael Showair
  • 3,092
  • 2
  • 22
  • 29