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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

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

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

其他回答

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

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

简单地在VC中添加以下到你的viewDidLoad:

self.automaticallyAdjustsScrollViewInsets = NO;

我也一直在想这个问题。我很确定这是iOS7的漏洞。 最终帮助我的,是xib中的观点顺序。在一个视图中,表视图被正确显示,在另一个视图中,表视图有额外的35px空间。两者之间唯一的区别(UITableView)是,在显示不好的视图中,UITableView是第一个子,而在显示正常的视图中,它是第二个。

这对我来说很有用,只是改变了视图的顺序。我真的不喜欢为了解决问题而添加额外的代码。

你可以检测你的应用是否运行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
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return CGFLOAT_MIN;
}

这就是所有的朋友们!