如何检测最后一个单元格

时间:2015-11-19 18:34:40

标签: ios uitableview

此表视图用于检测最后一个表格单元格的委托代码不起作用。

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


        if (indexPath.row == self.tableView(tableView, numberOfRowsInSection: 0) - 1) {
            ...
        }
   }

当我滚动时,代码确定的“最后一行”在列表中上下移动。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:0)

我认为tableView的节数大于1,因此您需要将该节进行计算(您应该确保numberOfSectionsnumberOfRows大于0):

let numberOfSections = self.tableView.numberOfSections

let numberOfRows = self.tableView.numberOfRowsInSection(numberOfSections-1)

if indexPath.row == numberOfRows - 1 && indexPath.section == numberOfSections - 1{
    ...
}

答案 1 :(得分:0)

尝试以下代码

if (indexPath == [NSIndexPath indexPathForRow:(numberOfRowsInLastSection - 1) inSection:(numberOfSections - 1)])
{
...
}

答案 2 :(得分:0)

在某些情况下,您的上一部分可能为空,因此您要查找包含单元格的最后一部分。这可以通过循环每个部分来完成,并且在每个部分中循环遍历每个单元。执行此操作时,请跟踪您遇到的单元格的最后一个indexPath,并且在完成循环时,您可以使用indexPath检索最后一个单元格。

这样的事情应该有效:

NSIndexPath *lastCellIndexPath;
for (NSInteger sectionIndex = self.tableView.numberOfSections - 1; sectionIndex >= 0; sectionIndex--) {
    if ([self.tableView numberOfRowsInSection:sectionIndex] > 0) {
        NSInteger section = sectionIndex;
        NSInteger row = [self.tableView numberOfRowsInSection:sectionIndex] - 1;
        lastCellIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
        break;
    }
}

// Retrieve your cell with the indexPath
...

答案 3 :(得分:0)

我的单元格包含一个在cell!.contLine.setNeedsDisplay() 内部绘制的UIView,并且输出对于起始和结束表格单元格而言是不同的。我发现如果我做以下事情......

contLine

...然后绘图是正确的。 (setNeedsDisplay是嵌入式UIView)。如果我在单元格上调用cell!.isEnd = (indexPath.row == (self.tableView(tableView, numberOfRowsInSection: 0) - 1)) ,那么它就不起作用了。所以我不得不打破这里的封装。

由于Ossie的建议,我也改变了检测代码,以便每次都更新单元格的状态。否则,重用的单元格状态可能是陈旧的。

updated