///方法1-->通过'<head>'将html字符串转化为 NSMutableAttributedString
class func getAttriFrom(str: String) -> NSMutableAttributedString {
let htmlStr = "<head><style>img{max-width:\(screenWidth-30)px !important; height:auto}</style></head>" + "<div style='font-size:13.7px'>" + str + "</div>"
print("方法1-->\(htmlStr)")
let attStr = try? NSMutableAttributedString.init(data: htmlStr.data(using: String.Encoding.utf16)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
return attStr ?? NSMutableAttributedString()
}
///方法2<此方法某些图片不会正常显示>-->通过'<html>'htmlStr 转化为 NSMutableAttributedString
class func getAttriFrom2(str: String) -> NSMutableAttributedString {
let headerS = "<html lang=\"zh-cn\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, nickName-scalable=no\"></meta><style>img{max-width: 100%; width:auto; height:auto;}body{text-align:justify;font-size:14px !important;}</style></head><body>"
let endS = "</body></html>"
let htmlStr = headerS + str + endS
print("方法2--->\(htmlStr)")
let attStr = try? NSMutableAttributedString.init(data: htmlStr.data(using: String.Encoding.utf8)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
return attStr ?? NSMutableAttributedString()
}
///方法3-->通过'<html>'htmlStr 转化为 NSMutableAttributedString
class func getAttriFrom3(str: String) -> NSMutableAttributedString {
let headerS = "<html lang=\"zh-cn\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, nickName-scalable=no\"></meta><style>img{max-width: \(screenWidth-20); !important; height:auto; margin: 0 auto; padding: 10px 10px 10px 0px; width: 100% !important;} body{text-align:justify;font-size:14px !important;}</style></head><body>"
let endS = "</body></html>"
let htmlStr = headerS + str + endS
//print("方法3--->\(htmlStr)")
var attStr = NSMutableAttributedString()
do {
attStr = try NSMutableAttributedString.init(data: htmlStr.data(using: String.Encoding.utf8)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch {
print(error)
}
return attStr
}