为 UITableView 部分 header 返回 CGFloat.leastNormalMagnitude 导致崩溃

Returning CGFloat.leastNormalMagnitude for UITableView section header causes crash

我为 iOS 8 制作了一个应用程序,其中一个页面使用 UITableView 分组。其中有多个部分使用 CGFloat.leastNormalMagnitude(或 Swift 2 及以下的 CGFloat.min)部分 header 和页脚高度以删除 "default" space。一切顺利,直到 iOS 9 和 10 中的应用程序 运行 崩溃并出现此错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'section header height must not be negative - provided height for section 0 is -0.00000'

不知何故,任何低于 1 的值(舍入的 0 除外)都被视为负数 - 并且使用 1 作为 return 值将使 header / 页脚 space 再次出现。

是否有解决此问题的方法?

提前致谢。

如果我将 header 部分的高度设置为:

,我会遇到同样的问题
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
tableView.estimatedSectionHeaderHeight = CGFloat.leastNormalMagnitude

但是如果我将控制器设置为 table 视图的委托 (UITableViewDelegate) 并实现:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return CGFloat.leastNormalMagnitude
}

然后就可以了

也许CGFloat.leastNonzeroMagnitude就是您所需要的!

我尝试了 tableView(_:heightForHeaderInSection:) 的几个值,发现:

  • leastNormalMagnitudeleastNonzeroMagnitude 将被视为减号(因此崩溃)。
  • 零将使 TableView return 成为页眉/页脚的默认高度。
  • 0 和 1 之间的任何值都将被视为减号。
  • 将 TableView return 设置为默认高度。
  • 任何超过 1 的值(例如 1.1)都会将页眉/页脚设置为实际高度。

我最终使用 1.1 解决了我的问题。

希望这对外面的人有所帮助!

我们在 iOS 9 使用 Swift 5 运行 Xcode 10.2 时经历了相同的 运行。事实证明,如果您在 estimatedHeightForHeaderInSection / estimatedHeightForFooterInSection 中 return CGFloat.leastNormalMagnitude 或 CGFloat.leastNonzeroMagnitude,它将在 iOS 9 台设备上崩溃。

您仍然可以 return heightForHeaderInSection / heightForFooterInSection 中的 leastNormalMagnitude 或 leastNonzeroMagnitude。

正如edopelawi上面指出的,任何小于1的值都将被视为负数,1将被视为默认的分组部分header/footer高度。如果设备 运行 iOS 10 或以下,我们最终 returning 1.000001 作为估计高度:


func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
    if #available(iOS 11.0, *) {
        return self.tableView(tableView, heightForHeaderInSection: section)
    } else {
        return max(1.000001, self.tableView(tableView, heightForHeaderInSection: section))
    }
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 0 {
        return 10
    }
    return CGFloat.leastNonzeroMagnitude
}

如果您实现了 viewForHeader 和 viewForFooter,您就不必作弊。

我个人 return 0.1f 当我想隐藏页眉时 and/or 例如页脚。 此示例将完全隐藏页眉和页脚,无需 space 填充,您可以从中添加自定义逻辑。

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
     return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}