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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

感谢@Aurelien Porte的回答。这是我的解决方案

产生此问题的原因:-

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

在ViewDidLoad: -

self.edgesForExtendedLayout = UIRectEdge.None

self.automaticallyAdjustsScrollViewInsets = false

不需要这样的东西:-

self.myTableview.contentInset = UIEdgeInsetsMake(-56, 0, 0, 0)

在highforheaderinsection委托中:-

if section == 0
    {
        return 1
    }
    else
    {
        return 40; // your other headers height value
    }

在viewForHeaderInSection委托中:-

if section == 0 
{  
   // Note CGFloat.min for swift
   // For Objective-c CGFLOAT_MIN 
   let headerView = UIView.init(frame: CGRectMake(0.0, 0.0, self.myShaadiTableview.bounds.size.width, CGFloat.min)) 
   return headerView
}
else
{ 
   // Construct your other headers here 
}

其他回答

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

确保您已经为表提供了约束。我没有遇到过类似的问题,在桌子底部有一个无法解释的填充物。

用这个吧,我觉得会有帮助…

 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
 {
    return 0.005f;// set this according to that you want...
 }

我假设这只是新UITableViewStyleGrouped样式的一部分。它存在于所有分组表视图中,似乎没有任何直接的方法来控制该空间。

如果这个空间是由一个UIView表示的,那么可以搜索UITableView的所有子视图来找到那个特定的视图并直接编辑它。然而,也有可能该空间只是标题和单元格开始之前的硬编码偏移量,没有任何方法来编辑它。

要搜索所有子视图(我将在表没有单元格时运行这段代码,以使它更容易阅读输出):

- (void)listSubviewsOfView:(UIView *)view {

    // Get the subviews of the view
    NSArray *subviews = [view subviews];

    // Return if there are no subviews
    if ([subviews count] == 0) return;

    for (UIView *subview in subviews) {

        NSLog(@"%@", subview);

        // List the subviews of subview
        [self listSubviewsOfView:subview];
    }
}

你可以检测你的应用是否运行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
}