从iOS7开始,在我的UITableView顶部有额外的空间它有一个UITableViewStyleGrouped样式。

这里有一个例子:

tableview从第一个箭头开始,有35个像素的无法解释的填充,然后绿色的头是一个由viewForHeaderInSection返回的UIView(其中section为0)。

有人能解释一下这个35像素的数量是从哪里来的吗?我如何才能在不切换到UITableViewStylePlain的情况下摆脱它?


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

我刚刚从接口生成器中删除了UITableView,再次创建它,奇怪的35px消失了。

它似乎有一个奇怪的错误在接口生成器。

其他回答

迅速回答……

如果在界面构建器中选择了表视图,并且在属性检查器中选择了样式“Grouped”,在视图控制器中输入以下代码来修复额外的标题空间问题。

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

我遇到了同样的问题,但是tableView在tableView单元格中。 上面的无数答案都不起作用。 一个非常奇怪而简单的东西起了作用:

-在为tableView分配委托之前,放置估计的高度!!

    override func awakeFromNib() {
        super.awakeFromNib()

        tableView.estimatedRowHeight = 58
        tableView.estimatedSectionHeaderHeight = 45
        tableView.estimatedSectionFooterHeight = 10
        tableView.dataSource = self
        tableView.delegate = self
    }

将估计放在委托分配之后,导致我的内部tableView在标题上方有一个奇怪的空白。 我希望它能帮助到这里的人。

2019答:

你只要这样做

tableView.contentInsetAdjustmentBehavior = .never

奇怪微妙的gotchya ->

现在表视图有一个非常奇怪的行为:

在有缺口(XR等)的设备上,它不会告诉你添加更多的插入,但只有当表格从屏幕的物理顶部开始时才会这样做。 如果你不是从屏幕顶部开始,它不会那样做,但是 这两种情况都是>>与safeAreaInsets .......无关这很让人困惑

所有这些都是完全没有记录的……你可以浪费几个小时来解决这个问题。

如果你确实需要从屏幕/表格的顶部开始测量,

事实上,简单地说:

tableView.contentInsetAdjustmentBehavior = .never

一个很好的例子是,当你在一个表格的顶部添加一些横幅或类似的东西时,这是现在很常见的,你只需要将表格的顶部插入设置为你的横幅/等在运行时的任何高度。

要做到这一点,必须使用

tableView.contentInsetAdjustmentBehavior = .never

电话:/

奖金陷阱

不要忘记,现在几乎总是动态加载一些信息(用户图片、描述等等),所以在信息到达之前不能将这些值设置为最终需要的值。另一个gotchya。:/

所以你会有这样的代码:

func setTableOffsetOnceFlagAreaSizeIsKnown() {
    tableView.contentInset.top = yourSpecialFlagViewUpTop.bounds.height
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    setTableOffsetOnceFlagAreaSizeIsKnown()
}

None of the previous answers worked for me. What did end up working for my situation (which was seeing that padding after dynamically adding a header to my Table View) was selecting the Navigation Bar from the Document Outline and rechecking the Translucent box (contrary to some answers that were saying to force it to be translucent). I had previously unchecked it because it had made my red look a little orange, but I could not try the solution of reordering the elements in the scene since the Table View was the only element in this scene. This solution works as long as you are okay with the Navigation Bar's color having a translucent layer over it. Hope this helps :)

只是取消勾选“调整滚动视图嵌入”对我来说没用。 后来,我尝试将tableview的头设置为nil,幸运的是,这是有效的。

self.tableView.tableHeaderView = nil