LayoutManager boundingRectForGlyphRange: inTextContainer: does not work for all rows

I have a UILabel with a tweet string, including mentions of other users.

Hey @stephen and @frank and @Jason1. 

I try to use every mention so that I can load this user profile. I found the code from another SO post ( How to find a CGRect for a substring of text in UILabel? ), Which I could use to find the position of each mention in a string. However, this usually does not work for the last or last two mentions in a post.

Method from SO post (slightly modified):

 - (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]; } 

Then, in touchesEnded: I touchesEnded: over each mention, get the range on the main line and check if the touch is inside this 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}} 

And this works great most of the time, however @ Jason1 is not suitable. I changed the order of the names, and it was always the last. My shortcut wraps around, but it still sometimes matches the names on the 2nd and 3rd lines. Is there a setting or something that I am missing? I tried changing the size and font of the shortcuts, but no luck. Here I am in a real loss.

+7
ios objective-c
Jul 26 '14 at 11:14
source share
1 answer

The fix for this is not to set a height limit when initializing an NSTextContainer. Use a very large number instead.

 NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(self.myLabel.bounds.size.width, CGFLOAT_MAX)]; 
+10
Oct 08 '14 at 16:20
source share



All Articles