How do I get the total number of glyphs that are in NSLayoutManager
?
I was making a cursor layer to overlay on a custom text view like this:
func moveCursorToGlyphIndex(glyphIndex: Int) {
// get bounding rect for glyph
var rect = self.layoutManager.boundingRectForGlyphRange(NSRange(location: glyphIndex, length: 1), inTextContainer: view.textContainer)
rect.origin.y = self.textContainerInset.top
rect.size.width = cursorWidth
// set cursor layer frame to right edge of rect
cursorLayer.frame = rect
}
However, I wanted to make sure that glyphIndex
is not out of bounds. Something like this:
if glyphIndex < self.layoutManager.glyphCount { // doesn't work
// ...
}
I couldn't find the right property by trial and error, though, and searching online didn't show any SO answers.
I finally did find it in buried in the documentation (and now it seems obvious), but since it took a long time, I decided I would add a Q&A here.
Use the numberOfGlyphs
property, as in
layoutManager.numberOfGlyphs
This is demonstrated in the Text Layout Programming Guide documentation here.