我有一個類似字符串的推文,包括提及其他用戶的UILabel。layoutManager boundingRectForGlyphRange:inTextContainer:不適用於所有字符串
Hey @stephen and @frank and @Jason1.
我試圖讓每個提到可點擊,所以我可以加載該用戶的配置文件。我發現了另一個SO帖子(How do I locate the CGRect for a substring of text in a UILabel?)中的一些代碼,我可以使用它來查找字符串中每個提及的位置。但它通常不適用於帖子中的最後或最後兩個提及。
從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行的名稱。有沒有設置或我錯過了什麼?我試過改變標籤的大小和字體,但沒有運氣。我在這裏真的很失落。
你解決了嗎?如果有任何問題,請分享解決方案。 –