boundingRectWithSize计算文字高度不准问题

在项目中遇到了计算label高度不对的情况,参照https://www.jianshu.com/p/c615a76dace2
我自己试验了下,\r\n这种不会导致计算错误,重要的是boundingRectWithSize方法官方注释就说了:
You can use this method to compute the space required to draw the string. The constraints you specify in the size parameter are a guide for the renderer for how to size the string. However, the actual bounding rectangle returned by this method can be larger than the constraints if additional space is needed to render the entire string. Typically, the renderer preserves the width constraint and adjusts the height constraint as needed.
In iOS 7 and later, this method returns fractional sizes (in the size component of the returned rectangle); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.
翻译:
可以使用此方法计算绘制字符串所需的空间。在size参数中指定的约束是呈现器如何调整字符串大小的指南。但是,如果需要额外的空间来呈现整个字符串,则此方法返回的实际边框可能比约束更大。通常,渲染器保留宽度约束,并根据需要调整高度约束。

在ios7及以后版本中,该方法返回小数大小(在返回矩形的大小组件中);要使用返回的size to size视图,必须使用ceil函数将其值提升到最近的整数。

即,用ceil将小数向上取整来解决问题

你可能感兴趣的:(boundingRectWithSize计算文字高度不准问题)