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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

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

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

希望能有所帮助。

其他回答

在iOS系统中,我在滚动视图中设置了tableview。当我在同一个屏幕上点击“返回”时滚动视图在顶部占用更多空间..为了解决这个问题,我使用了:

 self.automaticallyAdjustsScrollViewInsets = false

一个布尔值,指示视图控制器是否应自动调整其滚动视图嵌入。 默认值为true,该值允许视图控制器根据状态栏、导航栏、工具栏或选项卡栏所占用的屏幕区域来调整其滚动视图嵌入。如果您想自己管理滚动视图插入调整,例如当视图层次结构中有多个滚动视图时,则设置为false。

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

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

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

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

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

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

如果你选择UITableViewStyleGrouped的样式,你需要实现Header和Footer高度委托方法,并且返回值需要大于0;是这样的:

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

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

根据苹果的文档:

当将视图分配给此属性时,将该视图的高度设置为 一个非零值。表视图只尊重您的高度 视图的框架矩形;它调整你的头视图的宽度 自动匹配表视图的宽度。

斯威夫特5

如果你有一个分组UITableView,你想要一个tableHeaderView:

在将视图分配给tableView之前。tableHeaderView,设置该视图的高度为一个非零值,例如:

// Set the initial height of your custom view to the smallest value  
myTableHeaderView.frame.size.height = .leastNonzeroMagnitude

// Assign your custom view to the header view
tableView.tableHeaderView = myTableHeaderView

// Set width constraint, height should grow based on your view. 
tableView.tableHeaderView!.widthAnchor.constraint(equalTo: tableView.widthAnchor).isActive = true

不需要使用contentInsets或处理委托方法。

tableView.contentInsetAdjustmentBehavior = .never

是解决方案为我(iOS12 / xcode 10)在一个普通的表视图与头