【发布时间】:2014-07-26 11:14:45
【问题描述】:
我有一个带有类似字符串的推文的 UILabel,包括其他用户的提及。
Hey @stephen and @frank and @Jason1.
我试图让每个提及都可以点击,以便我可以加载该用户的个人资料。我从另一个 SO 帖子 (How do I locate the CGRect for a substring of text in a UILabel?) 中找到了一些代码,我可以使用这些代码来定位字符串中每个提及项的位置。但是,它通常不适用于帖子中的最后或最后 2 次提及。
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];
}
然后,在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, 0}, {49.809998, 20.553001}}
rect for @Jason1 is {{0, 0}, {0, 0}}
这在大多数情况下都很好用,但是 @Jason1 不匹配。我已经改变了名字的顺序,它总是最后一个。我的标签确实会换行,但有时仍会匹配第 2 行和第 3 行的名称。是否有设置或我缺少的东西?我试过改变标签的大小和字体,但没有运气。我在这里真的很茫然。
【问题讨论】:
-
你解决了吗?如果您有任何解决方案,请分享。
标签: ios objective-c