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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

如果自我。automcallyadjustsscrollviewinsets = NO;不为你工作,确保tableview头或section头的高度是CGFLOAT_MIN而不是0。

例如,如果你想让tableview头0高,你可以这样做:

    CGRect frame = self.tableViewHeader.frame;
    frame.size.height = CGFLOAT_MIN; //not 0
    self.tableView.tableHeaderView.frame = frame;
    self.tableView.tableHeaderView = self.tableViewHeader;

希望能有所帮助。

其他回答

你可以检测你的应用是否运行iOS7或更高版本,并在你的表视图委托中添加这两个方法(通常在你的UIViewController代码中)

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

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

这可能不是一个优雅的解决方案,但对我来说是可行的

斯威夫特版本:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return CGFloat.leastNormalMagnitude
}

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

对于iOS 15,在viewDidLoad中尝试以下解决方案:

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

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

与此完全无关

在我的例子中,在Storyboard的原型可视化中有一个不需要的名为HeaderView的单元格,当我删除它时,一切都很好。

这些答案或变通办法都帮不了我。大多数都在处理tableView本身。引起问题的是我添加tableView或collectionView到的视图。这就是我解决问题的方法:

斯威夫特5

edgesForExtendedLayout = []

我把它放到viewDidLoad中,烦人的间隙消失了。希望这能有所帮助。