首先停止滚动:
webView.scrollView.isScrollEnabled = false
webView.scrollView.showsVerticalScrollIndicator = false
webView.scrollView.showsHorizontalScrollIndicator = false
webView.scrollView.bounces = false
webView.loadHTMLString(dataHtmlString, baseURL: nil)
制作webView高度约束的出口,并通过计算其高度给出其值:
webviewHeightConst.constant = (dataHtmlString.htmlAttributedString()?.height(withConstrainedWidth: yourwidthcont))!
这个扩展计算高度
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
var found = false
html.beginEditing()
html.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, html.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
if (value != nil) {
let oldFont = value as! UIFont
let newFont = oldFont.withSize(16)
html.addAttribute(NSFontAttributeName, value: newFont, range: range)
found = true
}
}
if !found{
// No font was found - do something else?
}
html.endEditing()
return html
}
}