对于给定的NSRange,我想找到一个CGRect在UILabel对应的的字形NSRange.例如,我想CGRect在"快速的棕色狐狸跳过懒狗"这句话中找到包含"狗"字样的字样.

诀窍是,UILabel有多行,而文本确实attributedText如此,所以找到字符串的确切位置有点困难.
我想在我的UILabel子类上写的方法看起来像这样:
- (CGRect)rectForSubstringWithRange:(NSRange)range;
Run Code Online (Sandbox Code Playgroud)
细节,对于有兴趣的人:
我的目标是能够创建一个具有UILabel的确切外观和位置的新UILabel,然后我可以制作动画.我已经把剩下的事情搞清楚了,但特别是这一步让我暂时退缩了.
到目前为止我尝试解决问题的方法是:
UITextView和UITextField而不是UILabel.我敢打赌,对此的正确答案涉及以下其中一项:
NSLayoutManager和textContainerForGlyphAtIndex:effectiveRange更新:这是一个github要点,我已经尝试了迄今为止解决这个问题的三件事:https://gist.github.com/bryanjclark/7036101
我有一个像字符串一样的推文的UILabel,包括其他用户的提及.
Hey @stephen and @frank and @Jason1.
Run Code Online (Sandbox Code Playgroud)
我试图让每个提及都可以点击,这样我就可以加载该用户的个人资料.我从另一个SO帖子中找到了一些代码(如何找到UGRabel中文本子字符串的CGRect?),我可以使用它来查找字符串中每个提及的位置.但是,它通常不适用于帖子中的最后一个或最后两个提及.
来自SO帖子的方法(稍加修改):
- (CGRect)boundingRectForCharacterRange:(NSRange)range
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.myLabel.attributedText];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.myLabel.bounds.size];
textContainer.lineFragmentPadding = 0;
[layoutManager addTextContainer:textContainer];
NSRange glyphRange;
// Convert the range for glyphs.
[layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
}
Run Code Online (Sandbox Code Playgroud)
然后,在touchesEnded:,我循环每次提及,获取主字符串中的范围,并检查触摸是否在CGRect内.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = touches.allObjects[0];
for (NSString *mention in self.mentions) { …Run Code Online (Sandbox Code Playgroud) 我有一个NSTextField,里面有一个句子.我想为句子中的每个单词找到一个rect(理想情况下)或位置,以便在那些位置(NSTextField之外)执行操作.
在NSTextView/UITextView中这样做似乎是可以实现的与NSLayoutManager.boundingRectForGlyphRange,但没有NSLayoutManager是NSTextView(和UITextView的)都似乎更具挑战性的一点.
在NSTextField中找到给定单词的位置的最佳方法是什么?