美文网首页iOS Dev
Swift 如何计算UILabel中字符串的高度

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

作者: ba78fbce98d5 | 来源:发表于2016-02-14 12:20 被阅读4168次

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

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.

相关文章

网友评论

    本文标题:Swift 如何计算UILabel中字符串的高度

    本文链接:https://www.haomeiwen.com/subject/cwzukttx.html