这里我是给String写了一个类扩展
import Foundation
import UIKit
extension String{
func sizeWithText(font: UIFont, size: CGSize) -> CGSize {
let attributes = [NSAttributedStringKey.font: font]
let option = NSStringDrawingOptions.usesLineFragmentOrigin
let rect:CGRect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil)
return rect.size;
}
}
调用时候 直接用字符串调用即可