Search code examples
iosuitextviewnslayoutmanager

enumerateLineFragmentsForGlyphRange:withBlock: returns word fragments


I'm using a UITextView to display some text. In laying out the text, I enumerate the lines of text using the enumerateLineFragmentsForGlyphRange:withBlock: method.

NSInteger shrunkNumberOfLines = 3;
__block NSMutableString *shortenedText = [NSMutableString new];
__block NSInteger currentLine = 0;
__block BOOL needsTruncation = NO;

[detailsTableViewCell.descriptionTextView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, text.length) usingBlock:^(CGRect rect, CGRect usedRect, NSTextContainer *textContainer, NSRange glyphRange, BOOL *stop) {
  if (currentLine < shrunkNumberOfLines) {
    NSRange stringRange = ((glyphRange.length + glyphRange.location) <= text.length) ? glyphRange : NSMakeRange(glyphRange.location, (text.length - glyphRange.location));
            NSString *appendString = [text substringWithRange:stringRange];
            NSLog(@"%@", appendString);
            [shortenedText appendString:appendString];
            currentLine += 1;
  } else {
    needsTruncation = YES;
    *stop = YES;
  }
}];

However, I'm running into a weird bug: oftentimes, the text that gets displayed in the textview doesn't line up with the text that I see in that appendString.

For example, the text in the textfield might say something like:

President Obama offered a 
blueprint for deeper American
engagement in the Middle East.

...but looking at my NSLog statements, those appendStrings are something like:

President Obama offered a blu
eprint for deeper American en
gagement in the Middle East.

I've tried a bunch of things - playing with hyphenationFactor, making sure that the textContainerInsets are correct, etc - but I can't figure this out. What's causing invalid line breaks in the enumerateLineFragmentsForGlyphRange:withBlock: method?


Solution

  • While I'm still not sure what caused the underlying issue above, I've at least found something that solves the symptom: https://stackoverflow.com/a/19603172/686902