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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

具体来说,为了从顶部移除tableviewHeader空间,我做了这些更改:

YouStoryboard。storyboard > YouViewController >选择TableView >大小检查器>内容插入-设置为never。

其他回答

这段代码对我来说很有用,对我来说最好的答案是用objective-C写的,所以我把它转换成Swift。

针对Swift 4.0+

self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: .leastNonzeroMagnitude))

只需将其写入viewDidLoad(),它就会像一个咒语一样工作。

对于iOS 15+,上面的一个将不起作用,所以使用这个:-

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

对于iOS 15+,如果你想为你的整个项目应用更改,那么使用这个:-

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    if #available(iOS 15.0, *) {
        UITableView.appearance().sectionHeaderTopPadding = 0.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

与此完全无关

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

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

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
    if #available(iOS 15.0, *) {
        tableView.sectionHeaderTopPadding = 0
    }

放上这段代码,就可以了

如果你使用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