'sizeWithFont(_:constrainedToSize:lineBreakMode:)' 不可用:使用 -boundingRectWithSize:options:attributes:context:

'sizeWithFont(_:constrainedToSize:lineBreakMode:)' is unavailable: Use -boundingRectWithSize:options:attributes:context:

我必须根据其文本扩展 TextView 的大小,但它显示了问题但我无法修复它所以请帮助我修复此 issue.I post 代码是什么我试过了。

var size: CGSize = text.sizeWithFont(UIFont.boldSystemFontOfSize(13), constrainedToSize: textSize, lineBreakMode:NSLineBreakMode.ByWordWrapping)

我把this ObjC question的答案翻译成了Swift;可能让您感到困惑的是您需要将 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