因此,我试图获得与NSTextView中特定字符的位置相对应的NSPoint或NSRect.这就是我到目前为止所做的(效果不佳,结果似乎有些不可预测.
NSRange theTextRange = [[theTextView layoutManager] glyphRangeForCharacterRange:[theTextStorage editedRange] actualCharacterRange:NULL];
NSRect theTextRect = [[theTextView layoutManager] boundingRectForGlyphRange:theTextRange inTextContainer:[theTextView textContainer]];
Run Code Online (Sandbox Code Playgroud)
返回的rect boundingRectForGlyphRange:inTextContainer:是容器坐标.如果要相对于文本视图获取rect,则需要对此进行调整:
NSRange theTextRange = [[textView layoutManager] glyphRangeForCharacterRange:textRange actualCharacterRange:NULL];
NSRect layoutRect = [[textView layoutManager] boundingRectForGlyphRange:theTextRange inTextContainer:[textView textContainer]];
NSPoint containerOrigin = [textView textContainerOrigin];
layoutRect.origin.x += containerOrigin.x;
layoutRect.origin.y += containerOrigin.y;
Run Code Online (Sandbox Code Playgroud)