我必须根据文本扩展TextView的大小,但它显示了问题,但我无法修复它,因此请帮助我修复此问题。我发布了我尝试的代码。
var size: CGSize = text.sizeWithFont(UIFont.boldSystemFontOfSize(13), constrainedToSize: textSize, lineBreakMode:NSLineBreakMode.ByWordWrapping)
最佳答案
我把答案从this ObjC question翻译成Swift;可能让你绊倒的是你需要将String
转换成NSString
。
斯威夫特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
斯威夫特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
关于ios - 'sizeWithFont(_:constrainedToSize:lineBreakMode :)'不可用:使用-boundingRectWithSize:options:attributes:context:,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36374137/