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 )
本文介绍了一个Swift函数,用于计算给定文本和字体条件下的文本矩形尺寸。通过使用NSString的boundingRect方法,此函数能够帮助开发者预估界面中文本框所需的空间大小。
1793

被折叠的 条评论
为什么被折叠?



