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

时间:2016-04-02 13:54:01

标签: ios swift uifont

我必须根据文本扩展TextView的大小,但它已显示问题,但我无法修复它,所以请帮我解决这个问题。我发布了我尝试过的代码。

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

1 个答案:

答案 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