利用UILable 加载富文本并计算高度-Swift
lazy var contentDesc : UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 13)
label.textColor = UIColor.black
label.numberOfLines = 0
label.text = "---"
return label
}()
contentDesc.attributedText = self.getAttriFrom(str: translatePara.content!)
//富文本处理的逻辑,包含图片超出屏幕范围内的处理
func getAttriFrom(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: \(YYScreenWidth-25); width:auto; height:auto;}body{text-align:justify;font-size:14px !important;}</style></head><body>"
let endS = "</body></html>"
let htmlStr = headerS + str + endS
let attStr = try? NSMutableAttributedString.init(data: htmlStr.data(using: String.Encoding.utf8)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
return attStr ?? NSMutableAttributedString()
}
//测量高度并布局文本
let size = (contentDesc.text! as NSString).boundingRect(with: CGSize(width: Int(YYScreenWidth-20), height:Int.max ), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 13)], context: nil)
mContentWidth = size.width
mContentHeight = size.height
contentDesc.snp.makeConstraints { (make) in
make.left.equalTo(news_title.snp.left)
make.top.equalTo(news_time.snp.bottom).offset(20)
make.right.equalTo(news_source.snp.right)
make.height.equalTo(size.height)
}