从 HTML 计算 NSAttributedString 的大小

Calculate size of NSAttributedString from HTML

我正在使用 UITextView 来显示来自给定 HTML 的 NSAttributedString,它可以包括粗体、斜体、列表、标记、上标和下标等元素。

目前,下面的代码仅适用于文本段落,但一旦我开始添加更复杂的元素(例如列表和换行符),大小调整就会完全关闭。

// Create the NSMutableAttributedString from given HTML
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                          NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithData:data options:options
                               documentAttributes:nil error:nil];

// Max size for the text container (no limit on height)
CGSize bounds = CGSizeMake(320.0, CGFLOAT_MAX);

// Set the font and size for better rendering results
UIFont *font = [UIFont fontWithName:@"Roboto" size:14.0];
NSDictionary *attrFont = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
NSRange range = NSMakeRange(0, str.length);
[str addAttributes:attrFont range:range];

// Calcualte the size of the UITextView based on the above parameters
CGRect rect = [str boundingRectWithSize:bounds options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|        NSStringDrawingUsesDeviceMetrics context:nil];

我做了一些搜索并找到了这个线程,但是在尝试了那里的建议之后它似乎仍然没有用,想知道是否有人知道更好的方法来做到这一点?

好吧,经过多次摆弄,我发现尺寸实际上是正确的,但是 UITextView 有一些填充/插入导致溢出。在 textView 上设置以下内容解决了问题

[self.textView setTextContainerInset:UIEdgeInsetsZero];
self.textView.textContainer.lineFragmentPadding = 0;