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

希望能有所帮助。

其他回答

我假设这只是新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];
    }
}

自我。automcallyadjustsscrollviewinsets = NO;

这在iOS 11中已弃用,所以你应该使用new属性 contentInsetAdjustmentBehavior在你的代码中,它应该修复这个问题。

if #available(iOS 11.0, *) {
    collectionView.contentInsetAdjustmentBehavior = .never
}

在UIScrollView中添加了一个名为contentInsetAdjustmentBehavior的新属性,用于确定调整内容偏移量

我的回答将是更一般的答案,但也可以应用在这个问题上。

如果根视图(ViewController的)或根视图的第一个子视图(子视图)是UIScrollView(或UIScrollView本身)的子类,并且如果

self.navigationController.navigationBar.translucent = YES;

框架将自动设置预先计算的contentInset。


为了避免这种情况,你可以这样做

self.automaticallyAdjustsScrollViewInsets = NO;

但在我的情况下,我不能这样做,因为我正在实现SDK,其中有UIView组件,可以由其他开发人员使用。那个UIView组件包含UIWebView(它有UIScrollView作为第一个子视图)。如果该组件被添加为UIViewController的视图层次结构中的第一个子组件,自动嵌入将被系统应用。

在添加UIWebView之前,我已经通过添加frame(0,0,0,0)来修复这个问题。

在这种情况下,系统没有找到UIScrollView的子类作为第一个子视图,并没有应用insets

对于ios7,如果你在视图控制器中分配tableview,你可以查看

self.edgesForExtendedLayout = UIRectEdgeNone;

你的问题似乎和我的相似

更新:

iOS 9.x中的Swift:

self.edgesForExtendedLayout = UIRectEdge.None

Swift 3:

self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)

2021年Xcode 12.3更新

要解决这个问题,需要禁用标准节页脚。 下面的代码片段可以完成这项工作:

override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    return nil
}

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

的使用

tableView.contentInsetAdjustmentBehavior = .never

与此完全无关