# iOS 使用 boundingRect 计算 UILabel 的高度不准确的问题

**URL:** https://www.shiqidu.com/t/topic/636
**Category:** 开发调优
**Tags:** Swift
**Created:** [2019 年9 月 4 日 04:03 UTC](https://www.shiqidu.com/t/topic/636 "2019-09-04T04:03:37Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### 作者： ![Eureka](https://www.shiqidu.com/user_avatar/www.shiqidu.com/eureka/32/5_2.png) [@Eureka](https://www.shiqidu.com/u/Eureka)
#### 发布日期： [2019 年9 月 4 日 04:03 UTC](https://www.shiqidu.com/t/topic/636/1 "2019-09-04T04:03:37Z")

</div>

写了个cell，需要返回label的高度，但是使用 boundingRect 方法计算，一直都显示不全被折叠，计算方法如下

```swift
let titleHeight = model.title?.boundingRect(with: textMaxSize, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil).height

```

然后网上搜到说是因为中文标点导致的计算不准，推荐使用 `sizeThatFits` 方法

```swift
let label = UILabel()
label.font = font
label.numberOfLines = 0
label.text = model.content
let contentHeight = label.sizeThatFits(CGSize(width: CGFloat(ScreenWidth - 2 * mainMargin - 45), height: maxContentHeight)).height

```

然并卵，后来打印高度，发现都是浮点数，后来使用 ceil 方法进一取整后问题解决。
