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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

如果你在iOS 15或更高版本中遇到这个问题,请执行以下操作:

if #available(iOS 15.0, *) {
    self.tableView.sectionHeaderTopPadding = 0
}

其他回答

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return CGFloat.leastNonzeroMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return CGFloat.leastNonzeroMagnitude
}
set
  override func viewDidLoad() {
  self.tableView.delegate = self
  self.tableView.dataSource = self
}

只是取消勾选“调整滚动视图嵌入”对我来说没用。 后来,我尝试将tableview的头设置为nil,幸运的是,这是有效的。

self.tableView.tableHeaderView = nil

如果你使用snapkit,那么代码在这里。


self.tableView.snp.makeConstraints { make in
    make.top.equalToSuperview().inset(-35)
    make.leading.trailing.equalToSuperview().inset(0)
    make.bottom.equalTo(self.view.safeAreaLayoutGuide)
}

XCode 13.2.1和swift 5.0

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委托的视图。