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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

这是使用Swift 3的iOS 10的解决方案:

你可以通过实现UITableViewDelegate中的以下方法来去除顶部和底部填充。

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

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

其他回答

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

在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上测试。

希望能有所帮助。

我检查了所有的答案。没有一个对我有效。我所要做的就是

self.myTableView.rowHeight = UITableViewAutomaticDimension
self.myTableView.estimatedRowHeight = 44.0

此外,这个问题并没有发生在tableView的顶部。它发生在tableView每个部分的顶部。

这个问题只发生在iOS9上。我们的应用在iOS10和iOS 11上运行良好。

我强烈推荐你看看这个很棒的问题和它的顶级答案:

在UITableView中使用自动布局进行动态单元格布局和可变行高

在ios7中,你的视图开始于屏幕的上方,而不是导航栏的下方。它非常简单的设置到底部的导航栏。检查这个答案的解决方案,这不是同一个问题,但非常相关的你。

Swift 4代码: 对于没有section header的tableview,你可以添加以下代码:

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

你会得到标题间距为0。

如果你想要一个特定高度的头文件,传递该值:

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

和viewForHeaderinSection委托的视图。

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

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