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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

自我。automcallyadjustsscrollviewinsets = NO;

这在iOS 11中已弃用,所以你应该使用new属性 contentInsetAdjustmentBehavior在你的代码中,它应该修复这个问题。

if #available(iOS 11.0, *) {
    collectionView.contentInsetAdjustmentBehavior = .never
}

在UIScrollView中添加了一个名为contentInsetAdjustmentBehavior的新属性,用于确定调整内容偏移量

其他回答

自我。automcallyadjustsscrollviewinsets = NO;

这在iOS 11中已弃用,所以你应该使用new属性 contentInsetAdjustmentBehavior在你的代码中,它应该修复这个问题。

if #available(iOS 11.0, *) {
    collectionView.contentInsetAdjustmentBehavior = .never
}

在UIScrollView中添加了一个名为contentInsetAdjustmentBehavior的新属性,用于确定调整内容偏移量

override func viewWillAppear(animated: Bool) {
        self.edgesForExtendedLayout = UIRectEdge.None

 //  OR

self.sampleTableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);

   //OR

 self.automaticallyAdjustsScrollViewInsets = false
        }

根据苹果iOS7的过渡指南,滚动视图的内容嵌入是自动调整的。 automcallyadjustsscrollviewinsets的默认值设置为YES。

拥有UITableView的UIViewController应该将这个属性设置为NO。

self.automaticallyAdjustsScrollViewInsets = NO;

这样就可以了。

编辑1:

也可以尝试

self.navigationController.navigationBar.translucent = YES;

这也删除了顶部的额外填充。

还有另一种方式……但我喜欢它,因为它避免了硬编码任何高度值。

在UITableViewStyleGrouped表(静态或动态)中,只需在tableView中分配所需的高度(_:highightforheaderinsection)。我计算的新高度基于底部填充为节头标签。

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    var height = UITableViewAutomaticDimension

    if section == 0, let header = tableView.headerViewForSection(section) {
        if let label = header.textLabel {
            // get padding below label
            let bottomPadding = header.frame.height - label.frame.origin.y - label.frame.height
            // use it as top padding
            height = label.frame.height + (2 * bottomPadding)
        }
    }

    return height
}

在iOS 9和Xcode 7.3上测试。

希望能有所帮助。

所以我尝试了所有的方法,这次没有一个有用。我的案例是iOS 9上的分组表视图。我不知道为什么以及如何发现这个,但对我来说,用UIView设置tableViewHeader至少有0.01的高度是可行的。CGRectZero没有帮助,什么都没有帮助:

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