【发布时间】:2016-08-21 16:09:19
【问题描述】:
我正在使用 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
如您所见,我的宽度是正确的(我是强制的),但我的高度不正确,我不知道为什么。
感谢和问候, 埃里克
【问题讨论】: