Detect when UITableView has scrolled to the bottom

前端 未结 4 1844
感动是毒
感动是毒 2020-12-13 09:01

Is the following post still the accepted way of detecting when an instance of UITableView has scrolled to the bottom [in Swift], or has it been altered (as in: improved) sin

相关标签:
4条回答
  • 2020-12-13 09:28

    We can avoid using scrollViewDidScroll and use tableView:willDisplayCell

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.section == tableView.numberOfSections - 1 &&
            indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1 {
            // Notify interested parties that end has been reached
        }
    }
    

    This should work for any number of sections.

    0 讨论(0)
  • 2020-12-13 09:44

    try this

     func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let height = scrollView.frame.size.height
        let contentYoffset = scrollView.contentOffset.y
        let distanceFromBottom = scrollView.contentSize.height - contentYoffset
        if distanceFromBottom < height {
            print(" you reached end of the table")
        }
    }
    

    or you can find in this way

    if tableView.contentOffset.y >= (tableView.contentSize.height - tableView.frame.size.height) {    
        //you reached end of the table
    }
    
    0 讨论(0)
  • 2020-12-13 09:44

    In Swift 4

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
      let isReachingEnd = scrollView.contentOffset.y >= 0
          && scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)
    }
    

    If you implement expandable UITableView/UICollectionView, you may need to check scrollView.contentSize.height >= scrollView.frame.size.height

    0 讨论(0)
  • 2020-12-13 09:51

    Swift 3

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row + 1 == yourArray.count {
            print("do something")
        }
    }
    
    0 讨论(0)
提交回复
热议问题