Calculate Height Of NSAttributedString Containing

2019-08-01 09:00发布

问题:

I am using NSAttributedString to display HTML text using the following code.

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)
}

I now want to calculate the height of the string, In the HTML, I am using the HTML tags such as p, strong, em, ul > li, ol > li.

I tried the following code.

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)

This returns 462 which is way lesser then actual height, how to correctly calculate the height for this?

Thanks.

回答1:

My solution did work, The problem was that I was incorrectly setting the size of scrollview, fixing the height of scroll view fixed my problem.

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)