UITableView检测最后一个单元格

War*_*ard 17 iphone scroll detect uitableview ios

如何检测何时UITableView滚动到底部以便最后一个单元格可见?

Mic*_*ler 40

在里面tableView:cellForRowAtIndexPath:tableView:willDisplayCell:forRowAtIndexPath:像这样:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ...

    NSInteger sectionsAmount = [tableView numberOfSections];
    NSInteger rowsAmount = [tableView numberOfRowsInSection:[indexPath section]];
    if ([indexPath section] == sectionsAmount - 1 && [indexPath row] == rowsAmount - 1) {
        // This is the last cell in the table
    }

    ...

}
Run Code Online (Sandbox Code Playgroud)

  • numberOfSections调用datasource numberOfSectionsInTableView,numberOfRowsInSection调用datasource numberOfRowsInSection.在我的实现中,它崩溃了,显示了这个执行的递归日志. (3认同)

Art*_*pie 23

tableView:willDisplayCell:forRowAtIndexPath:在UITableViewDelegate中实现该方法,并检查它是否是最后一行.


sam*_*ize 14

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger lastSectionIndex = [tableView numberOfSections] - 1;
    NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;
    if ((indexPath.section == lastSectionIndex) && (indexPath.row == lastRowIndex)) {
        // This is the last cell
    }
}
Run Code Online (Sandbox Code Playgroud)


Bar*_*zyk 5

创建优雅的扩展UITableView:

extension UITableView {

    func isLast(for indexPath: IndexPath) -> Bool {

        let indexOfLastSection = numberOfSections > 0 ? numberOfSections - 1 : 0
        let indexOfLastRowInLastSection = numberOfRows(inSection: indexOfLastSection) - 1

        return indexPath.section == indexOfLastSection && indexPath.row == indexOfLastRowInLastSection
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if tableView.isLast(for: indexPath) {
        //do anything then
    }

    return cell
}
Run Code Online (Sandbox Code Playgroud)