//MARK:- 计算 HTML 代码高度(可 包含图片)
func getHTMLHeight(byStr str:String?, font:UIFont? =UIFont.systemFont(ofSize:16), lineSpacing:CGFloat? =10, width:CGFloat) ->CGFloat{
let attributedString =setAttributedString(str, font: font)
let contextSize = attributedString?.boundingRect(with:CGSize(width: width, height:CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context:nil).size
return contextSize?.height??0.0
}
/// html 富文本设置
/// - Parameters:
/// - str: html 未处理的字符串
/// - font: 设置字体
/// - lineSpacing: 设置行高
/// - Returns: 默认不将 \n替换<br/>返回处理好的富文本
func setAttributedString(_str:String?, font:UIFont? =UIFont.systemFont(ofSize:16), lineSpacing:CGFloat? =5) ->NSMutableAttributedString? {
var str = str
//如果有换行,把\n替换成<br/>
// str = str?.replacingOccurrences(of: "\n", with: "
")//如果有需要请去掉注释 // .replacingOccurrences(of: "\n", with: "<br/>")
//利用 CSS 设置HTML图片的宽度
str ="img{width:\(SCREENW * 0.8)!important;height:auto}\(str ?? "")" //.replacingOccurrences(of: "\n", with: "<br/>")
var htmlString: NSMutableAttributedString? = nil
do{
if let data = str?.data(using: .utf8) {
htmlString = try NSMutableAttributedString(data: data, options: [
NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)
], documentAttributes:nil)
}
}catch{
}
//设置富文本字的大小
if let font = font {
htmlString?.addAttributes([
NSAttributedString.Key.font: font
], range:NSRange(location:0, length: htmlString?.length??0))
}
//设置行间距
let paragraphStyle =NSMutableParagraphStyle()
paragraphStyle.lineSpacing= lineSpacing!
htmlString?.addAttribute(.paragraphStyle, value: paragraphStyle, range:NSRange(location:0, length: htmlString?.length??0))
return htmlString
}
有一个需求是 后台数据只能给返回HTML内容(有文字 有图片)高度 我们除了显示这部分还需要加入原生的元素
用的时候 直接 textview.attributedText =富文本设置方法的内容就可了
没办法啊自己算高度吧
就是感觉有一一点不准。。。。
网友评论