Swift & OC 解析HTML
首选大家可能都会使用 WKWebView
,但是针对不同项目可能会有不同的问题,嵌套页面内使用WKWebView
计算高度就是一个问题,上下均有不同控件,页面渲染时,加载HTML高度时,需要WebView
完全加载完才知道对应高度。所以PASS掉改方案。
第三方库? 每个标签解析,然后在组合,在使用控件显示,工程量太大,而且针对HTML
代码又不是完全固定格式,所以也PASS掉。
最终选择的是富文本形式,加载渲染速度都够快,而且符合需求(点击图片浏览和视频播放 可能需要单独在开发,不是本文重点,省略了……)。还可以很好的计算HTML
高度(包含内嵌图片)。
直接上修改后的Swift代码(感谢原作者提供的OC代码):
对源代码稍微改动:源代码计算高时没有包含行高设置,在显示时有行高设置,所以导致内容缺失,不能显示全部内容,所以修改了下,也去掉了重复代码
/// 计算 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? = 10) -> NSMutableAttributedString? {
var str = str
//如果有换行,把\n替换成<br/>
//如果有需要请去掉注释 // .replacingOccurrences(of: "\n", with: "<br/>")
//利用 CSS 设置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 {
}
//设置富文本字的大小
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
}