iOS Dev

Swift 如何计算UILabel中字符串的高度

2016-02-14  本文已影响4168人  ba78fbce98d5

主要通过以下两个方法计算:

NSString
<pre>
func boundingRectWithSize(size: CGSize, options: NSStringDrawingOptions, attributes: [NSObject : AnyObject]!, context: NSStringDrawingContext!) -> CGRect
</pre>

NSAttributedString
<pre>
func boundingRectWithSize(size: CGSize, options: NSStringDrawingOptions, context: NSStringDrawingContext?) -> CGRect
</pre>

扩展:

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

    let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
    
    return boundingBox.height
}

}
</pre>

<pre>
extension NSAttributedString {
func heightWithConstrainedWidth(width: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.max)
let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)

return ceil(boundingBox.height)

}
}
</pre>


注意点:

1.xib和storyboard指定的font和代码中指定的font是否相同。

2.view的width确定。

3.以上方法,只负责计算文字的高度,如若字符串需要改变行间距,则适当修改options。 详见官方文档


happy coding happy life.
welcom to my blog.

上一篇 下一篇

猜你喜欢

热点阅读