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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

如果你使用snapkit,那么代码在这里。


self.tableView.snp.makeConstraints { make in
    make.top.equalToSuperview().inset(-35)
    make.leading.trailing.equalToSuperview().inset(0)
    make.bottom.equalTo(self.view.safeAreaLayoutGuide)
}

XCode 13.2.1和swift 5.0

其他回答

我喝了和arielyz一样的药。一旦我把UITableView移到不是父视图的第一个子视图,它就消失了。空间是20px,不是35。

我无法在肖像xib中重现它,只能在风景xib中重现。如果我可以在一个简单的演示应用程序中重现它,我将稍后提交一个雷达漏洞。

我认为制作UIEdgeInsets -35 0 0 0是乏味的。在我的例子中,我实现了tableView: hightforheaderinsection:方法,它有可能返回0。

当我把0改成0.1f时,问题就消失了。

只需将你的tableview(或使它开始)固定在视图的绝对顶部。多余的空间正好是导航条的高度。

还有另一种方式……但我喜欢它,因为它避免了硬编码任何高度值。

在UITableViewStyleGrouped表(静态或动态)中,只需在tableView中分配所需的高度(_:highightforheaderinsection)。我计算的新高度基于底部填充为节头标签。

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    var height = UITableViewAutomaticDimension

    if section == 0, let header = tableView.headerViewForSection(section) {
        if let label = header.textLabel {
            // get padding below label
            let bottomPadding = header.frame.height - label.frame.origin.y - label.frame.height
            // use it as top padding
            height = label.frame.height + (2 * bottomPadding)
        }
    }

    return height
}

在iOS 9和Xcode 7.3上测试。

希望能有所帮助。

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return CGFLOAT_MIN;
}

这就是所有的朋友们!