我实现了EstimatedHeightForRowAt indexPath后,UITableView崩溃了吗?

lik*_*eSo 3 uitableview ios swift

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    let cellHeight = self.promotionListViewList[indexPath.row].tableViewHeight.value
    if cellHeight < 0 {
        return 1.0
    } else {
        return cellHeight
    } 
}
Run Code Online (Sandbox Code Playgroud)

当我取消注释此方法并在iPhone5或iPad2上运行项目时,出现以下异常:

“表格视图行的高度不能为负-为索引路径提供的高度”

然后应用崩溃

但为什么?

我没有用这种方法产生负值。

如果我发表评论,那什么也没发生。

Fra*_*iro 5

如果您根据此stackoverflow使用自动布局,请回答/sf/ask/1287804451/

  1. 估计行高为1.0会导致异常:“ NSInternalInconsistencyException”,原因:“表视图行高不能为负...”
  2. 估计小于1.0也会产生奇怪的结果。

  3. 在2.0和实际工作之间进行估算就可以了,没有任何异常(尽管出于优化的原因2.0可能是一个糟糕的选择-您希望尽可能地接近实际)。

  4. 仅当估计的行高大于实际的行高时,才会发生约束异常。您离实际越近,发生异常的可能性就越小。出现异常之前您的估计可能有多远与几个不同的因素有关:实际的行高,行的位置等。

此解决方案应避免出现以下异常:

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    let cellHeight = self.promotionListViewList[indexPath.row].tableViewHeight.value
    if cellHeight < 0 {
        return 1.01
    } else {
        return cellHeight
    } 
}
Run Code Online (Sandbox Code Playgroud)