UITableView Detecting Last Cell

前端 未结 8 748
广开言路
广开言路 2021-01-31 10:46

How can I detect when a UITableView has been scrolled to the bottom so that the last cell is visible?

8条回答
  •  日久生厌
    2021-01-31 11:26

    Create elegant extension for 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
        }
    }
    

    Example of usage:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        if tableView.isLast(for: indexPath) {
            //do anything then
        }
    
        return cell
    }
    

提交回复
热议问题