Swift:boundingRectWithSize为多行标签返回错误的高度

时间:2016-08-21 16:09:20

标签: ios swift string uilabel

我在String类上使用扩展来获取在多行标签中显示字符串所需的高度。

extension String {
    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: CGFloat.max)

        let option = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)

        let boundingBox = self.boundingRectWithSize(constraintRect, options: option, attributes: [NSFontAttributeName: font], context: nil)
        print("ex width \(boundingBox.width)")
        print("ex height \(boundingBox.height)")
        return boundingBox.height
    }
}

我在heightForRowAtIndexPath

中调用它
let myRandomString = "My baby looks like she's ashamed and wants to apologise for something bad she did."
let labelWidth = UIScreen.mainScreen().bounds.width-16
let labelHeight = myRandomString.heightWithConstrainedWidth(labelWidth,font: UIFont.boldSystemFontOfSize(17))

我得到了:

ex width 359.0
ex height 40.57421875

但是当我使用xcode的view debuging选项时,我得到了这个: enter image description here

这就是我的UILabel的设置方式: enter image description here

你可以看到我的宽度是正确的(我强迫它),但我的身高不正确,我无法弄清楚原因。

谢谢和问候, 埃里克

1 个答案:

答案 0 :(得分:0)

仅限多行使用.UsesLineFragmentOrigin