Houssam Hammoud
Houssam Hammoud

Reputation: 77

Swift 3.0 get the height of html string in UILABEL

I have list on rows on UITableView, and each row contain html string come from the apis, I am using

 let str = try NSMutableAttributedString(data: d,
                                                    options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                                    documentAttributes: nil)

But I cannot get the real height of each html string? I tried to use Label.sizeThatFits but it did not work.

How can I get the real height of html string from UILabel?

Thanks

Upvotes: 2

Views: 1672

Answers (1)

Irshad Ahmad
Irshad Ahmad

Reputation: 1383

Try this Function

'
func heightForHtmlString(_ text: NSMutableAttributedString, font:UIFont, labelWidth:CGFloat) -> CGFloat{
    let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: labelWidth, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.attributedText = text as NSAttributedString
    label.sizeToFit()
    return label.frame.height
}'

Upvotes: 2

Related Questions