我必须根据文本扩展TextView的大小,但它已显示问题,但我无法修复它,所以请帮我解决这个问题。我发布了我尝试过的代码。
var size: CGSize = text.sizeWithFont(UIFont.boldSystemFontOfSize(13), constrainedToSize: textSize, lineBreakMode:NSLineBreakMode.ByWordWrapping)
答案 0 :(得分:5)
我将答案从this ObjC question翻译成斯威夫特;绊倒你的是你需要将String
投射到NSString
。
Swift 4
let text = "Hello"
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let maxSize = CGSize(width: 100, height: CGFloat.greatestFiniteMagnitude)
let size = (text as NSString).boundingRect(with: maxSize,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: [NSFontAttributeName:font],
context: nil)
.size
Swift 3
let text = "Hello"
let font = UIFont.systemFontOfSize(UIFont.systemFontSize())
let maxSize = CGSize(width: 100, height: CGFloat.max)
let size = (text as NSString).boundingRectWithSize(maxSize,
options: [.UsesLineFragmentOrigin, .UsesFontLeading],
attributes: [NSFontAttributeName:font],
context: nil)
.size