popeyelau / wiki

📒Wiki for many useful notes, source, commands and snippets.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Swift String 高度计算

popeyelau opened this issue · comments

import UIKit

    func heightOfString(withConstrainedWidth width: CGFloat,
                        attributes: [NSAttributedString.Key: Any],
                        insets: UIEdgeInsets = .zero) -> CGFloat {
        
        let constraintRect = CGSize(width: width - insets.left - insets.right, height: .greatestFiniteMagnitude)
        
        let boundingBox = self.boundingRect(with: constraintRect,
                                            options: [.usesLineFragmentOrigin, .usesFontLeading],
                                            attributes: attributes, context: nil)
        
        return ceil(boundingBox.height) + insets.top + insets.bottom
    }

    var trimed: String {
        return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    }
}
//使用
let str = "注意该函数和 ReadAtLeast 的区别:ReadFull 将 buf 读满;而 ReadAtLeast 是最少读取 min 个字节。"
let insets = UIEdgeInsets(top: 20, left: 8, bottom: 20, right: 8)
//行间距
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
//样式
let attributes:[NSAttributedString.Key: Any] = [.font: UIFont.preferredFont(forTextStyle: .caption2), .paragraphStyle: paragraphStyle]
//计算高度
let textHeight = data.desc.trimed.heightOfString(withConstrainedWidth: bounds.width, attributes: attributes, insets: insets)