我在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选项时,我得到了这个:
你可以看到我的宽度是正确的(我强迫它),但我的身高不正确,我无法弄清楚原因。
谢谢和问候, 埃里克
答案 0 :(得分:0)
仅限多行使用.UsesLineFragmentOrigin
。