【问题标题】:layoutManager boundingRectForGlyphRange:inTextContainer: does not work for all stringslayoutManager boundingRectForGlyphRange:inTextContainer: 不适用于所有字符串
【发布时间】: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


【解决方案1】:

解决此问题的方法是在初始化 NSTextContainer 时不设置高度约束。请改用非常大的数字。

NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(self.myLabel.bounds.size.width, CGFLOAT_MAX)];

【讨论】:

  • 在iOS7上,你应该使用这种方法。但是在iOS8及以上,你可以愉快地使用label.size。
  • FWIW,我刚刚通过在 iOS 13.5 上将高度设置为最大修复了这样的错误。
  • 天啊,像魔术一样工作!你拯救了我的一天!!
猜你喜欢
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
相关资源
最近更新 更多