This code work perfectly.
But I have a problem that I want to load HTML data and change it's font.
And I try to using NSAttributedString to set UIFont, it doesn't work to me.
What should I do to change HTML data font, and calculate it's height correct?
Thanks.
func loadHtmlContent() {
let articleHtmlData = "<head><style>img{width:300px !important;height:225px !important}</style></head>"+articleContent
do {
let attrStr = try NSMutableAttributedString(
data: articleHtmlData.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
attrStr.enumerateAttribute(
NSFontAttributeName,
in:NSMakeRange(0,attrStr.length),
options:.longestEffectiveRangeNotRequired) { value, range, stop in
let f1 = value as! UIFont
let f2 = UIFont(name:"Helvetica", size:20)!
if let f3 = applyTraitsFromFont(f1, to:f2) {
attrStr.addAttribute(
NSFontAttributeName, value:f3, range:range)
}
}
self.articleHeight = self.heightForHtmlString(attrStr)
self.articleContentTextView.attributedText = attrStr
} catch let error {
print(error)
}
}
func heightForHtmlString(_ text: NSAttributedString) -> CGFloat {
let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width-(16*4), height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = UIFont(name: "PingFangTC-Regular", size: 20.0)
label.attributedText = text
label.sizeToFit()
return label.frame.height
}