ios – layoutManager boundingRectForGlyphRange:inTextContainer:不适用于所有字符串

ios – layoutManager boundingRectForGlyphRange:inTextContainer:不适用于所有字符串,第1张

概述我有一个像字符串一样的推文的UILabel,包括其他用户的提及. Hey @stephen and @frank and @Jason1. 我试图让每个提及都可以点播,这样我就可以加载该用户的个人资料.我发现了一些来自另一个SO帖子(How do I locate the CGRect for a substring of text in a UILabel?)的代码,我可以使用它来找到字符串中每 我有一个像字符串一样的推文的UILabel,包括其他用户的提及.
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 aboverect 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行的名称.有没有设置或我缺少的东西?我试过改变标签的大小和字体,但没有运气.我在这里真的很亏.

解决方法 解决此问题的方法是在初始化NSTextContainer时不设置高度约束.请使用非常大的数字.
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(self.myLabel.bounds.size.wIDth,CGfloat_MAX)];
总结

以上是内存溢出为你收集整理的ios – layoutManager boundingRectForGlyphRange:inTextContainer:不适用于所有字符串全部内容,希望文章能够帮你解决ios – layoutManager boundingRectForGlyphRange:inTextContainer:不适用于所有字符串所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1101793.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存