方法如下:
// 计算字符串长度
func sizeWithText(text: String, font: UIFont, size: CGSize) -> CGRect {
let attributes = [NSAttributedString.Key.font: font]
let option = NSStringDrawingOptions.usesLineFragmentOrigin
let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil)
return rect;
}
如何调用:比如计算一个label的text长度
let rect = sizeWithText(text: label?.text ?? "", font: UIFont.systemFont(ofSize: 14), size: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
那么,rect.width就是我们要的label的字体长度