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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

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

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

其他回答

我对它做了一些改动这似乎是设置tableView的tableHeaderView = nil的副作用。

因为我的tableView有一个动态出现的tableHeaderView,当我需要隐藏tableHeaderView,而不是做self.tableView.tableHeaderView = nil;,我做:

self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.01f)];

我更喜欢这个解决方案,而不是设置一个有点随意的contentInset。因为我使用了contentInset。也是动态Top。当我重新计算contentInset时,必须记得删除额外的35px。顶部很乏味。

如果我添加一个高度很小的tableHeaderView,它就能解决这个问题

    let v = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.000000001))
    tableViewDocuments.tableHeaderView = v

设置内容插入到从来没有解决我的问题。

我假设这只是新UITableViewStyleGrouped样式的一部分。它存在于所有分组表视图中,似乎没有任何直接的方法来控制该空间。

如果这个空间是由一个UIView表示的,那么可以搜索UITableView的所有子视图来找到那个特定的视图并直接编辑它。然而,也有可能该空间只是标题和单元格开始之前的硬编码偏移量,没有任何方法来编辑它。

要搜索所有子视图(我将在表没有单元格时运行这段代码,以使它更容易阅读输出):

- (void)listSubviewsOfView:(UIView *)view {

    // Get the subviews of the view
    NSArray *subviews = [view subviews];

    // Return if there are no subviews
    if ([subviews count] == 0) return;

    for (UIView *subview in subviews) {

        NSLog(@"%@", subview);

        // List the subviews of subview
        [self listSubviewsOfView:subview];
    }
}

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

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

希望能有所帮助。