Swift & OC 解析HTML
首選大家可能都會使用 WKWebView
,但是針對不同項目可能會有不同的問題,嵌套頁面內(nèi)使用WKWebView
計算高度就是一個問題缩滨,上下均有不同控件呐萨,頁面渲染時,加載HTML高度時底哥,需要WebView
完全加載完才知道對應(yīng)高度咙鞍。所以PASS掉改方案。
第三方庫趾徽? 每個標(biāo)簽解析续滋,然后在組合,在使用控件顯示孵奶,工程量太大疲酌,而且針對HTML
代碼又不是完全固定格式,所以也PASS掉。
最終選擇的是富文本形式朗恳,加載渲染速度都夠快湿颅,而且符合需求(點擊圖片瀏覽和視頻播放 可能需要單獨在開發(fā),不是本文重點粥诫,省略了……)油航。還可以很好的計算HTML
高度(包含內(nèi)嵌圖片)。
直接上修改后的Swift代碼(感謝原作者提供的OC代碼):
對源代碼稍微改動:源代碼計算高時沒有包含行高設(shè)置怀浆,在顯示時有行高設(shè)置谊囚,所以導(dǎo)致內(nèi)容缺失,不能顯示全部內(nèi)容揉稚,所以修改了下秒啦,也去掉了重復(fù)代碼
/// 計算 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 富文本設(shè)置
/// - Parameters:
/// - str: html 未處理的字符串
/// - font: 設(shè)置字體
/// - lineSpacing: 設(shè)置行高
/// - Returns: 默認(rèn)不將 \n替換<br/> 返回處理好的富文本
func setAttributedString(_ str: String?, font: UIFont? = UIFont.systemFont(ofSize: 16), lineSpacing: CGFloat? = 10) -> NSMutableAttributedString? {
var str = str
//如果有換行,把\n替換成<br/>
//如果有需要請去掉注釋 // .replacingOccurrences(of: "\n", with: "<br/>")
//利用 CSS 設(shè)置HTML圖片的寬度
str = "<head><style>img{width:\(width * 0.97) !important;height:auto}</style></head>\(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 {
}
//設(shè)置富文本字的大小
if let font = font {
htmlString?.addAttributes([
NSAttributedString.Key.font: font
], range: NSRange(location: 0, length: htmlString?.length ?? 0))
}
//設(shè)置行間距
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing!
htmlString?.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: htmlString?.length ?? 0))
return htmlString
}