计算包含 HTML 的 NSAttributedString 的高度

Calculate Height Of NSAttributedString Containing HTML

我正在使用 NSAttributedString 来显示 HTML 使用以下代码的文本。

do {
    let html = "<span style=\"font-family: Montserrat-ExtraLight; font-size: 14; line-height: 1.5;\">\(clinic.profile!)</span>"
    let clinicProfile = try NSAttributedString(
        data: (html.data(using: String.Encoding.unicode, allowLossyConversion: true)!),
        options: [
            NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType
        ],
        documentAttributes: nil
    )
    contentView.attributedText = clinicProfile
    scrollView.addSubview(contentView)
} catch {
    print(error)
}

我现在想计算字符串的高度,在HTML中,我使用了HTML标签,例如p, strong, em, ul > li, ol > li.

我尝试了以下代码。

let size = CGSize(width: view.frame.width, height: 2000)
let boundingBox = contentView.attributedText.boundingRect(
    with: size,
    options: [.usesLineFragmentOrigin, .usesFontLeading, .usesDeviceMetrics],
    context: nil
)
print(boundingBox.height)

这个returns462比实际身高小很多,请问如何正确计算这个高度?

谢谢。

我的解决方案确实有效,问题是我错误地设置了滚动视图的大小,修复了滚动视图的高度解决了我的问题。

let size = CGSize(width: view.frame.width, height: 2000)
let boundingBox = contentView.attributedText.boundingRect(
    with: size,
    options: [.usesLineFragmentOrigin, .usesFontLeading, .usesDeviceMetrics],
    context: nil
)
print(boundingBox.height)