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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

我有一个VC与容器在它(btw是一个导航控制器的一部分),并嵌入其中是一个TableVC。

选择我的TableVC,查看属性面板:

取消勾选自动调整滚动插入 取消检查顶部栏下的延伸边

然后我设置了容器相对于父视图的自动约束:

容器的观点。top = ParentView。顶边

这为我完成了以下任务:

保持桌面拉到顶部,但就在我的导航栏下面 刷新后,表返回到这个位置,而不是像以前那样在导航栏下向上+ 在实际的底部滚动表底部后,不缺它

我用这个设置进行了大量的试验和错误,但我最终发现了lekksi @移除UITableView单元格前的空白空间发布的这些小细节

其他回答

None of the previous answers worked for me. What did end up working for my situation (which was seeing that padding after dynamically adding a header to my Table View) was selecting the Navigation Bar from the Document Outline and rechecking the Translucent box (contrary to some answers that were saying to force it to be translucent). I had previously unchecked it because it had made my red look a little orange, but I could not try the solution of reordering the elements in the scene since the Table View was the only element in this scene. This solution works as long as you are okay with the Navigation Bar's color having a translucent layer over it. Hope this helps :)

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

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

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

当你需要隐藏你的tableHeaderView时,你应该使用这段Swift 3代码:

tableView.tableHeaderView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0.0, height: CGFloat.leastNormalMagnitude)))

Swift3

如果你使用分组表,然后做以下事情。 这将删除顶部空间。

    var frame = CGRect.zero
    frame.size.height = .leastNormalMagnitude
    self.tableView.tableHeaderView = UIView(frame: frame)
    self.tableView.tableFooterView = UIView(frame: frame)

如果你仍然得到这个问题,那么它将删除默认的内容偏移从顶部。

[永不设置内容插入] https://i.stack.imgur.com/fjxOV.png

这段代码对我来说很有用,对我来说最好的答案是用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
    }
}