在NSAttributedString的drawWithRect中查找最后一个可见行索引

我正在从用户提供的文本创建一个pdf,但是当文本对于页面来说太大时我有问题,我必须计算文本将被切断的位置,以便我可以将下一个块移动到下一页。 我使用此代码绘制属性文本:

CGRect rect = CGRectFromString(elementInfo[@"rect"]); NSString *text = elementInfo[@"text"]; NSDictionary *attributes = elementInfo[@"attributes"]; NSAttributedString *attString = [[NSAttributedString alloc] initWithString:text attributes:attributes]; [attString drawWithRect:rect options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine context:nil]; 

我怎样才能到达“最后一条可见线”的位置?

这个解决方案的作用是检查你的文本是否适合具有给定框架和字体的UITextView ,如果没有,它会删除字符串中的最后一个单词并再次检查它是否合适。 它继续这个过程,直到它适合给定的帧。 一旦它达到给定的大小,就会返回应该拆分字符串的索引。

 - (NSUInteger)pageSplitIndexForString:(NSString *)string inFrame:(CGRect)frame withFont:(UIFont *)font { CGFloat fixedWidth = frame.size.width; UITextView *textView = [[UITextView alloc] initWithFrame:frame]; textView.text = string; textView.font = font; CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)]; CGRect newFrame = textView.frame; newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height); while (newFrame.size.height > frame.size.height) { textView.text = [self removeLastWord:textView.text]; newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)]; newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height); } NSLog(@"Page one text: %@", textView.text); NSLog(@"Page two text: %@", [string substringFromIndex:textView.text.length]); return textView.text.length; } 

删除最后一个字的方法:

 - (NSString *)removeLastWord:(NSString *)str { __block NSRange lastWordRange = NSMakeRange([str length], 0); NSStringEnumerationOptions opts = NSStringEnumerationByWords | NSStringEnumerationReverse | NSStringEnumerationSubstringNotRequired; [str enumerateSubstringsInRange:NSMakeRange(0, [str length]) options:opts usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { lastWordRange = substringRange; *stop = YES; }]; return [str substringToIndex:lastWordRange.location]; } 

要使用此“ pageSplit ”方法,您可以调用它并根据提供的字符串的长度检查返回的索引。 如果返回的索引小于字符串的长度,则表示您需要拆分为第二页。

为了给予信用到期的一些功劳,我从其他几个SO答案中借用了代码( 如何根据其内容调整UITextView的大小?并获得NSString的最后一个字 )来提出我的解决方案。


根据您的评论,我编辑了我的答案,以便您可以发送详细信息并在要分割的字符串中找回索引。 您提供字符串,容器大小和字体,它将告诉您页面拆分将发生的位置(字符串中的索引)。