Ios 在UITextView中计算html内容高度失败

Ios 在UITextView中计算html内容高度失败,ios,swift,uitextview,nsattributedstring,Ios,Swift,Uitextview,Nsattributedstring,我使用带有自定义单元格的UITableView将HTML代码呈现为带有AttributeString的UITextView。UITextView适合单元格,我使用自动布局根据UITextView的内容获取动态高度 我在示例中使用的html是 <h1>hey this is a <a href="www.google.com">link</a><h1> calculateHeight函数: class func calculateHeight(te

我使用带有自定义单元格的UITableView将HTML代码呈现为带有AttributeString的UITextView。UITextView适合单元格,我使用自动布局根据UITextView的内容获取动态高度

我在示例中使用的html是

<h1>hey this is a <a href="www.google.com">link</a><h1>
calculateHeight函数:

class func calculateHeight(textView:UITextView, data:String) -> CGRect {

    var newFrame:CGRect!
    do {
        let attr = try NSAttributedString(data: data.data(using: String.Encoding.utf8)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        textView.attributedText = attr
    } catch {
        //Handle Exceptions
    }

    let fixedWidth = textView.frame.size.width
    textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    newFrame = textView.frame
    newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
    print("height \(newFrame.height)")
    return newFrame
}
此技术返回的高度似乎与动态高度返回的高度完全相同

html文本没有常规文本时会出现此问题


在计算高度之前,您可以尝试删除所有的
html标记
,如果无法以其他方式解决此问题,这是一个非常好的主意。谢谢你,我想你可以尝试使用WKWebView来加载你的html字符串,然后很好地计算高度。它也支持图像@QuocNguyen WKWebView对于这样的任务来说太重了this@QuocNguyen是的,我第一次尝试WKWebView,但它似乎太重,无法在多个UITableViewCell中使用
class func calculateHeight(textView:UITextView, data:String) -> CGRect {

    var newFrame:CGRect!
    do {
        let attr = try NSAttributedString(data: data.data(using: String.Encoding.utf8)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        textView.attributedText = attr
    } catch {
        //Handle Exceptions
    }

    let fixedWidth = textView.frame.size.width
    textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    newFrame = textView.frame
    newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
    print("height \(newFrame.height)")
    return newFrame
}