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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

我注意到这个问题有很多答案,这取决于你想要做什么,所以我将分享我的答案,以防有人想要同样的效果:

在我的视图控制器中,我有一个分组的UITableView,它的tableHeaderView由一个200点高的UIScrollView和一个单独的带有属性的UILabel组成,UILabel包含一个广告标题、价格、位置和发布的时间。下面是表视图的内容。

在分组表视图标头的默认维度下,“MORE INFO”标头远远低于“5天前”标签。我通过覆盖每个部分的页眉和页脚的高度来修复它(已经是上面的图像)。

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == kMoreInfoSection ? 33 : UITableViewAutomaticDimension;
}

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

我从@erurainon的评论中了解了覆盖高度,从https://stackoverflow.com/a/14404104/855680了解了UITableViewAutomaticDimension。我不需要设置self。automyadjustsscrollviewinsets在我的视图控制器中不像接受的答案所建议的那样为NO。

我也已经尝试设置UIEdgeInsets和给表视图一个负值的顶部,但它没有工作-整个表视图移动,包括tableHeaderView。

其他回答

根据苹果的文档:

当将视图分配给此属性时,将该视图的高度设置为 一个非零值。表视图只尊重您的高度 视图的框架矩形;它调整你的头视图的宽度 自动匹配表视图的宽度。

斯威夫特5

如果你有一个分组UITableView,你想要一个tableHeaderView:

在将视图分配给tableView之前。tableHeaderView,设置该视图的高度为一个非零值,例如:

// Set the initial height of your custom view to the smallest value  
myTableHeaderView.frame.size.height = .leastNonzeroMagnitude

// Assign your custom view to the header view
tableView.tableHeaderView = myTableHeaderView

// Set width constraint, height should grow based on your view. 
tableView.tableHeaderView!.widthAnchor.constraint(equalTo: tableView.widthAnchor).isActive = true

不需要使用contentInsets或处理委托方法。

故事板:

确保你的UITableView top约束没有说“Under top layout guide”。相反,它应该说“顶部空间:Superview”(Superview.Top)。

当然,在包含UITableView的UIViewController中,取消勾选“调整滚动视图Insets”。

我得到了以下的帮助:

YouStoryboard。>属性检查>取消勾选-调整滚动视图嵌入。

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

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

self.automaticallyAdjustsScrollViewInsets = NO;

这样就可以了。

编辑1:

也可以尝试

self.navigationController.navigationBar.translucent = YES;

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

我们有很多答案。

1)你可以在view didload中添加UIImageview

UIImageView * imbBackground = [UIImageView new];
[self.view addSubview:imbBackground];

2)可以设置页眉和页脚高度为0.1

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

3)您可以添加高度为0.1的页眉和页脚视图

tblCampaigns.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, tblCampaigns.bounds.size.width, 0.01f)];
tblCampaigns.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, tblCampaigns.bounds.size.width, 0.01f)];