func getStringRect(text:String, font:UIFont) -> CGRect {
let nsText: NSString = NSString( string: text )let size:CGSize = CGSize(width: UIScreen.main.bounds.width, height: 0)
let options:NSStringDrawingOptions = NSStringDrawingOptions.usesFontLeading
let boundRec = nsText.boundingRect(with: size, options: options, attributes: [NSFontAttributeName: font], context: nil)
return boundRec
}
使用范例:
let text: String = "abcabc"
let font: UIFont = UIFont.systemFont(ofSize: 14)
let cgRect: CGRect = getStringRect(text: text, font: font )
print( cgRect.width, cgRect.height )