详解iOS开发中UITableview cell 顶部空白的多种设置方法

这篇博客总结了在iOS开发中遇到UITableView顶部空白的常见原因及其解决方案,包括automaticallyAdjustsScrollViewInsets属性的设置、navigationBar的translucent属性、section header高度的陷阱以及tableview的header和footer设置问题。通过正确设置这些属性,可以避免UITableView在显示时出现不必要的空白区域。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我知道没人会主动设置这个东西,但是大家一定都遇到过这个问题,下面总结下可能是哪些情况:
- self.automaticallyAdjustsScrollViewInsets = NO;

iOS7在Controller中新增了automaticallyAdjustsScrollViewInsets这个属性,当设置为YES时(默认YES),如果视图里面存在唯一一个UIScrollView或其子类View,那么它会自动设置相应的内边距,这样可以让scroll占据整个视图,又不会让导航栏遮盖。

- navigationbar设置问题
  虽然表面上看是tableview顶部有空白,但实际上可能是因为navigationbar设置问题导致。
   self.navigationController.navigationBar.translucent = NO; 这个属性设为no之后,tableview会在上方留出64.f的位置给navigationbar,也有小概率导致这个问题。
  
- tableview section header高度设置问题
  这个应该是新手遇到的比较多的。起因是iOS奇葩的逻辑,如果你设置header(或者footer)高度是0的话,系统会认为你没设置,然后将其设置为40.f。所以需要将其设置为一个较小的数:

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

- tableview的header、footer设置问题
  和上一个很像是不是?没发现区别吗?那就再读一次看看。这次是tableview的header视图引起的,而不是section的header高度引起。
对于tableview,不仅每个section有header,tableview整体也有header和footer,API如下:

@property (nonatomic, strong, nullable) UIView *tableHeaderView; // accessory view for above row content. default is nil. not to be confused with section header
@property (nonatomic, strong, nullable) UIView *tableFooterView; // accessory view below content. default is nil. not to be confused with section footer
这个header和footer要比section的header要和谐一些,只要你不去主动碰它就没事,但是如果你碰了.基本上会被设置出40.f高的间距。出现如下任意一行代码均会引起这个问题:
 self.tableView.tableHeaderView = nil; 
 self.tableView.tableHeaderView = [[UIView alloc] init]; 
 self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero]; 
 self.tableView.tableFooterView = nil; 
 self.tableView.tableFooterView = [[UIView alloc] init]; 
 self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

footerView也不能设置,footer和header只要设置了任意一个都会使两个地方都出现空白。
   当然,如果有的时候真的只需要其中一个view的话该怎么办呢?请如下设置:

[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, 0.0001f)];
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, 0.0001f)];

说白了,还是得设置成一个很小的高度,而不是0才行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值