我有一个像字符串一样的推文的UILabel,包括其他用户的提及.
Hey @stephen and @frank and @Jason1.
我试图让每个提及都可以点播,这样我就可以加载该用户的个人资料.我发现了一些来自另一个SO帖子(How do I locate the CGRect for a substring of text in a UILabel?)的代码,我可以使用它来找到字符串中每个提及的位置.但是,它通常不适用于帖子中的最后一个或最后两个提及.
- (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]; }
然后,在touchesEnded:中,我循环每次提及,获取主字符串中的范围,并检查触摸是否在CGRect内.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = touches.allObjects[0]; for (NSString *mention in self.mentions) { NSRange range = [self.postText rangeOfString:mention options:NSCaseInsensitiveSearch]; CGRect rect = [self boundingRectForCharacterRange:range]; NSLog(@"rect for %@ is %@",mention,NSStringFromCGRect(rect)); } } // Output from above rect for @stephen is {{33.388,0},{72.471001,20.553001}} rect for @frank is {{143.021,{49.809998,20.553001}} rect for @Jason1 is {{0,{0,0}}
这大部分时间都很好用,但是@Jason1并没有得到匹配.我已经改变了名字的顺序,它总是最后一个.我的标签确实换行,但它有时仍会匹配第2行和第3行的名称.有没有设置或我缺少的东西?我试过改变标签的大小和字体,但没有运气.我在这里真的很亏.