2016-08-21 86 views
1

我在String类上使用扩展来获取在多行标签中显示我的字符串所需的高度。Swift:boundingRectWithSize为多行标签返回错误的高度

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选项观点我得到这个: enter image description here

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

正如你可以看到我的宽度是正确的(我强迫它),但我的身高是不正确的,我不明白为什么。

感谢和问候, 埃里克

回答

0

对于多只使用.UsesLineFragmentOrigin