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

这里有一个例子:

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

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


更新(回答):

在iOS 11及更高版本中:

tableView.contentInsetAdjustmentBehavior = .never

当前回答

我们有很多答案。

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)];

其他回答

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

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

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

我的回答将是更一般的答案,但也可以应用在这个问题上。

如果根视图(ViewController的)或根视图的第一个子视图(子视图)是UIScrollView(或UIScrollView本身)的子类,并且如果

self.navigationController.navigationBar.translucent = YES;

框架将自动设置预先计算的contentInset。


为了避免这种情况,你可以这样做

self.automaticallyAdjustsScrollViewInsets = NO;

但在我的情况下,我不能这样做,因为我正在实现SDK,其中有UIView组件,可以由其他开发人员使用。那个UIView组件包含UIWebView(它有UIScrollView作为第一个子视图)。如果该组件被添加为UIViewController的视图层次结构中的第一个子组件,自动嵌入将被系统应用。

在添加UIWebView之前,我已经通过添加frame(0,0,0,0)来修复这个问题。

在这种情况下,系统没有找到UIScrollView的子类作为第一个子视图,并没有应用insets

对于ios7,如果你在视图控制器中分配tableview,你可以查看

self.edgesForExtendedLayout = UIRectEdgeNone;

你的问题似乎和我的相似

更新:

iOS 9.x中的Swift:

self.edgesForExtendedLayout = UIRectEdge.None

Swift 3:

self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 0.0
}

这对我很管用。也可以根据section给出标题的高度。

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

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