返回 CGFloat.minimumNormalMagnitude for UITableView 节标题会导致崩溃



我为iOS 8制作了一个应用程序,该应用程序使用分组UITableView作为其页面之一。其中有多个部分使用 CGFloat.leastNormalMagnitude(或 Swift 2 及更低版本中的 CGFloat.min(作为节页眉和页脚高度来删除"默认"空格。一切都很顺利,直到该应用程序在iOS 9和10中运行,并出现此错误:

由于未捕获的异常"NSInternalInconsistencyException"而终止应用,原因:"节标题高度不得为负 - 如果节 0 的高度为 -0.00000">

不知何故,1下的任何值(四舍五入的0除外(都被视为负值 - 并且使用1作为返回值将使页眉/页脚空间再次出现。

有什么解决方法可以解决此问题吗?

提前谢谢。

我已经为tableView(_:heightForHeaderInSection:)尝试了几个值,并发现:

  • leastNormalMagnitudeleastNonzeroMagnitude 将被视为减号(因此崩溃(。
  • 零将使表视图返回默认高度作为页眉/页脚。
  • 0 到 1 之间的任何值都将被视为减号。
  • 一个将使表视图返回默认高度。
  • 任何超过一个(例如 1.1(都会将页眉/页脚设置为实际高度。

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

希望这会帮助那里的人!

我们在 iOS 9 上使用运行 Xcode 10.2 的 Swift 5 也经历了同样的体验。事实证明,如果您在estimatedHeightForHeaderInSection/estimatedHeightForFooterInSection中返回CGFloat.minimumNormalMagnitude或CGFloat.minimumNonzeroMagnitude,它将在iOS 9设备上崩溃。

您仍然可以在 heightForHeaderInSection/heightForFooterInSection 中返回 minimumNormalMagnitude 或 minimumNonzeroMagnitude。

正如 edopelawi 上面指出的,任何小于 1 的值都将被视为负值,而 1 将被视为默认分组节页眉/页脚高度。我们最终返回 1.000001 作为设备运行 iOS 10 或更低版本的估计高度:


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
}

如果我使用以下命令设置节标题高度,我会遇到同样的问题:

tableView.sectionHeaderHeight = UITableViewAutomaticDimension
tableView.estimatedSectionHeaderHeight = CGFloat.leastNormalMagnitude

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

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

然后它起作用

也许CGFloat.leastNonzeroMagnitude就是你需要的!

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

例如,当我想隐藏页眉和/或页脚时,我个人返回 0.1f。此示例将完全隐藏页眉和页脚,没有要填充的空间,您可以从中添加自定义逻辑。

- (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;
}

最新更新