popeyelau / wiki

📒Wiki for many useful notes, source, commands and snippets.
2 stars 0 forks source link

Swift String 高度计算 #6

Open popeyelau opened 5 years ago

popeyelau commented 5 years ago
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)