Не удалось вычислить высоту содержимого HTML в UITextView - PullRequest
0 голосов
/ 29 августа 2018

Я использую UITableView с пользовательской ячейкой для рендеринга HTML-кода в UITextView с AttributedString. UITextView соответствует ячейке, и я использую Auto-Layout для получения динамической высоты на основе содержимого UITextView.

HTML-код, который я использую для примера,

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

Кажется, что найденная высота неверна.

enter image description here

Я также попытался определить высоту базы содержимого для строки с помощью

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let text = content[indexPath.row]
    let tv = UITextView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bouds.width - 16 * 2, height: 1.0))
    tv.isScrollEnabled = false
    tv.textContainerInset = UIEdgeInsets.zero
    tv.textContainer.lineFragmentPadding = 0
    let height = TextContentCell.calculateHeight(textView: tv, data: text).height
    return height
}

Функция вычисления высоты:

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
}

Эта техника, похоже, возвращает ту же высоту, что и динамическая высота.

enter image description here

Эта проблема возникает с текстом HTML без обычного текста.

enter image description here

...