OGeek|极客世界-中国程序员成长平台

标题: ios - 在 NSAttributedString 的 drawWithRect 中查找最后一个可见的行索引 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 05:30
标题: ios - 在 NSAttributedString 的 drawWithRect 中查找最后一个可见的行索引

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

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

如何获得“最后一条可见线”所在的位置?



Best Answer-推荐答案


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

- (NSUInteger)pageSplitIndexForStringNSString *)string 
                              inFrameCGRect)frame 
                             withFontUIFont *)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(@"age one text: %@", textView.text);

    NSLog(@"age two text: %@", [string substringFromIndex:textView.text.length]);

    return textView.text.length;
}

删除最后一个单词的方法:

- (NSString *)removeLastWordNSString *)str
{
    __block NSRange lastWordRange = NSMakeRange([str length], 0);
    NSStringEnumerationOptions opts = NSStringEnumerationByWords | NSStringEnumerationReverse | NSStringEnumerationSubstringNotRequired;
    [str enumerateSubstringsInRange:NSMakeRange(0, [str length]) optionspts 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?Getting the last word of an NSString)中借用了代码来提出我的解决方案。


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

关于ios - 在 NSAttributedString 的 drawWithRect 中查找最后一个可见的行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28764651/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4