objective-ccocoanstextviewnslayoutmanager

NSTextView and determining glyph position


I am trying to define y axis position for certain lines and have label next to them in an NSTextView. I am using glyphRangeForCharacterRange.

It kind of works, but the text view can have a LOT of text (even ~4000-5000 lines) and is wrapped with insets. As I scroll to stuff that is out of view, the results are wrong. It seems to return values without wrapping, or so I figure. If I do an update on the positions while I have scrolled to corresponding text, they are calculated correctly.

This is the code without additional offsets:

NSRange characterRange = NSMakeRange(startPosition, length);
NSRange range = [[self.textView layoutManager] glyphRangeForCharacterRange:characterRange actualCharacterRange:nil];
label.frame = rect;

NSRect rect = [[self.textView layoutManager] boundingRectForGlyphRange:range inTextContainer:[self.textView textContainer]];

The same problem occurs if I try to set the label positions after the document awakes, so I calculate the labels on first keypress, which isn't too nice.

What would be the best way around this?


Solution

  • EDIT

    The answer to this problem was just to ensure the layout for the NSLayoutManager before retrieving glyph coordinates.

    [[_textView layoutManager] ensureLayoutForTextContainer:[_textView textContainer]];