为啥 UITableView 的最后一个单元格的高度用于剩余的空单元格?

Posted

技术标签:

【中文标题】为啥 UITableView 的最后一个单元格的高度用于剩余的空单元格?【英文标题】:Why does last cell's height of UITableView get used for remaining empty cells?为什么 UITableView 的最后一个单元格的高度用于剩余的空单元格? 【发布时间】:2013-03-08 13:02:22 【问题描述】:

我的单元格都有不同的高度,由用户输入的文本决定。

最后一个单元格的高度似乎决定(更改)所有剩余空白单元格的高度。

似乎没有为这些剩余的空单元格调用 heightForRowAtIndexPath,CFRAIP 也没有。

有谁知道如何解决这个问题或为什么会发生这种情况?

【问题讨论】:

这很奇怪:对 HFRAIP/CFRAIP 的调用次数应该与可见单元格的数量一样多,无论是否为空白。这不是你看到的吗? 不,只是调用我真正需要的单元格。从上次使用的单元格中清空它正在重用的维度。 【参考方案1】:

将这段代码放在放置Tableview的viewController的viewDidLoad中。

self.tableView.tableFooterView = [[UIView alloc] init];

【讨论】:

太棒了!但要纠正它.. 它应该是 self.tableView.tableFooterView = [[UIView alloc] init];【参考方案2】:

我也遇到了这个问题。这让我很沮丧。经过一番考虑,我认为它可能是 tableview 的一个特性,它显示空白单元格。使用空白单元格的最后一个单元格高度是合理的。否则,选择使用什么高度? 我认为显示黑色单元格是不可接受的。如果你像我一样不喜欢这种风格,你可以试试这个去掉空白单元格:

self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero]; 

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//then add view for separator line by yourself

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];
tableView.backgroundColor = self.tableView.backgroundColor;
self.tableView = tableView;

如果您必须显示空白单元格并控制高度,也许这是添加额外单元格的最简单方法/解决方法。例如:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
   return self.dataArray == nil || self.dataArray.count == 0 ? 1 : self.dataArray + 1;


 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    if(indexPath.count == self.dataArray.count) //the last cell
       cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
     else 
       cell = .... //as uausal
    

    return cell;
   

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    if(indexPath.count == self.dataArray.count)
      return 50;
    else 
    return xxx; //as usual
   
 

现在我们可以控制任意高度了!

希望对你有帮助。

您也可以参考链接:How can I modify the appearance of 'empty' cells in plain UITableView?

【讨论】:

以上是关于为啥 UITableView 的最后一个单元格的高度用于剩余的空单元格?的主要内容,如果未能解决你的问题,请参考以下文章

为啥 UITableView 自定义单元格的第一个单元格总是在 Xcode 中的动作事件上被调用两次

如何删除UITableView中最后一个单元格的最后一个边框?

向下滚动时,UITableview 看不到最后一个单元格

在 UITableView 中插入最后一行并平滑滚动

我在学习iOS的UITableView,为啥UITableView的最后一块单元格只能显示一半? [关闭]

UITableView 滚动到最后一个单元格只显示一半的单元格