美文网首页
计算富文本高度

计算富文本高度

作者: 授之以渔不如授之以鱼 | 来源:发表于2021-06-09 10:37 被阅读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.

    相关文章

      网友评论

          本文标题:计算富文本高度

          本文链接:https://www.haomeiwen.com/subject/oateeltx.html