UILable 加载富文本并计算高度-Swift

利用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 = ""
        let endS = ""
        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)
        }

你可能感兴趣的:(UILable 加载富文本并计算高度-Swift)