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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

对于第一部分,我们需要像这样设置tableHeaderView:

tableView.tableHeaderView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: .leastNonzeroMagnitude))

对于其他section,我们应该像这样设置highightforfooterinsection:

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

其他回答

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return CGFLOAT_MIN;
}

这就是所有的朋友们!

在尝试了一切之后,终于知道如何解决这个问题!

我注意到,由于某种原因,我的tableview的contenttoffset有一个'y'为-20,所以当配置我的tableview: 斯威夫特3/4

tableView.contentOffset = .zero

objective - c

self.tableView.contentOffset = CGPointMake(0, 44);

iOS 15的解决方案:

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

修正:在整个项目中修正:

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

更多详细信息:在iOS 15中,表视图头部上有额外的填充

注意:这只适用于UITableView.Style.plain。

上面的很多答案都太俗气了。如果苹果决定修复这种意外的行为,它们在未来的任何时候都会崩溃。

问题的根源:

UITableView不喜欢头的高度为0.0。如果你要做的是有一个高度为0的标题,你可以跳到解决方案。 即使以后你给你的头分配了一个非0.0的高度,UITableView也不喜欢一开始就被分配一个高度为0.0的头。

解决方案:

然后,最简单可靠的修复方法是确保头高度在分配给表视图时不为0。

这样做是可行的:

// Replace UIView with whatever class you're using as your header below:
UIView *tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.tableView.bounds.size.width, CGFLOAT_MIN)];
self.tableView.tableHeaderView = tableViewHeaderView;

这样的事情会在某些时候(通常是在滚动之后)导致问题:

// Replace UIView with whatever class you're using as your header below:
UIView *tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
self.tableView.tableHeaderView = tableViewHeaderView;

对我来说,我尝试了所有的解决方案,但我在考虑为UITableView部分设置高度,它为我工作。(使用斯威夫特)

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