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

Find last visible line index in NSAttributedString's 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];

如何获取 "last visible line" 所在的位置?

此解决方案的作用是检查您的文本是否适合给定框架和字体的 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 答案 (How do I size a UITextView to its content? and Getting the last word of an NSString) 中借用了代码来提出我的解决方案。


根据您的意见,我编辑了我的答案以提供一种方法,您可以在其中发送详细信息并取回要拆分的字符串中的索引。您提供字符串、容器大小和字体,它会让您知道页面拆分的位置(字符串中的索引)。