计算富文本高度

2021-06-09  本文已影响0人  授之以渔不如授之以鱼
  func getLabelLayoutHeight(content: String, withTextFontSize mFontSize: CGFloat) -> CGFloat {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 5 // 段落高度
        let attributes = NSMutableAttributedString(string: content)
        attributes.addAttribute(.font, value: UIFont.systemFont(ofSize: mFontSize), range: NSRange(location: 0, length: content.count))
        attributes.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: content.count))
        
        let attSize = attributes.boundingRect(with: CGSize(width: kScreenWidth-129, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).size
        
        return attSize.height
    }
    
    func labelHeight(text: String) -> CGFloat {        // 注意这里的宽度计算,要根据自己的约束来计算
        let maxSize = CGSize(width: kScreenWidth-129, height: CGFloat(MAXFLOAT))
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .left
        paragraphStyle.lineBreakMode = .byWordWrapping
        //            paragraphStyle.lineSpacing = 5.0
        paragraphStyle.paragraphSpacing = 5.0
        let labelSize = NSString(string: text).boundingRect(with: maxSize,
                                                            options: [.usesFontLeading, .usesLineFragmentOrigin],
                                                            attributes:[.font : UIFont.systemFont(ofSize: 12), .paragraphStyle: paragraphStyle],
                                                            context: nil).size
        return labelSize.height
    }
    

两种方法都可以,如果是历遍加上换行符的话“\n”,记得减去一行间隙lineSpaing的高度5.

上一篇下一篇

猜你喜欢

热点阅读