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

希望能有所帮助。

其他回答

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

与此完全无关

故事板:

只需取消勾选:在视图控制器的选项中调整滚动视图嵌入

代码:

self.automaticallyAdjustsScrollViewInsets = false

另一个快速评论…甚至在XCode 6.1中,UIScrollViews, UITextViews和UITableViews顶部出现垂直空格的错误。

有时,修复此问题的唯一方法是进入Storyboard并拖动问题控件,使其不再是页面上的第一个子视图。

(感谢Oded为我指明了这个方向……我发表这篇评论,只是为了添加一些截图,以演示症状和解决方法。)

set
  override func viewDidLoad() {
  self.tableView.delegate = self
  self.tableView.dataSource = self
}

对我来说,这就是帮助我的东西。我也支持ios6。

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
}