【问题标题】:Detect when UITableView has scrolled to the bottom检测 UITableView 何时滚动到底部
【发布时间】:2016-08-18 09:59:00
【问题描述】:

以下帖子是否仍然是检测 UITableView 实例何时滚动到底部 [在 Swift 中] 的公认方法,或者它是否已被更改(如:改进)?

Problem detecting if UITableView has scrolled to the bottom

谢谢。

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    试试这个

     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")
        }
    }
    

    或者你可以这样找到

    if tableView.contentOffset.y >= (tableView.contentSize.height - tableView.frame.size.height) {    
        //you reached end of the table
    }
    

    【讨论】:

    • 谢谢@Anbu.Karthik。我可能会做。我震惊这样原始的方法在 2016 年仍然必须使用,但就这样吧。是什么阻止了工程师引入“func scrollViewDidScrollToBottom”功能?
    • 别担心@Anbu.Karthik,我只是在呻吟。
    • @Anbu.Karthik 您的回答帮助我确定了表格的滚动(表格结束)。我想这就是原因。
    • 如果表格中有标题,此解决方案将不起作用。
    • 我必须将 if 条件更改为 if distanceFromBottom &lt;= height 才能使其正常工作。
    【解决方案2】:

    斯威夫特 3

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row + 1 == yourArray.count {
            print("do something")
        }
    }
    

    【讨论】:

    • 此方案仅在有 1 个部分时有效。当节数较多时,需要将左侧的行数累加。
    • 这对我来说似乎是最好的答案
    • @kjoelbro 你得到了整个indexPath。您可以轻松确定表格视图的结束位置
    • if indexPath.section == COUNT_OF_SECTIONS - 1 { if indexPath.row + 1 == LAST_DATA_SET.count { print("do something")
    • 如果单元格很少,则在表格最初加载数据时调用 print 语句。绝对不推荐
    【解决方案3】:

    我们可以避免使用scrollViewDidScroll而使用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
        }
    }
    

    这应该适用于任意数量的部分

    【讨论】:

    • 我相信 tableView 会为它最初加载的每个单元格调用此方法。例如。如果有 26 个单元格并且它首先加载 13 个,它将在第一次 reloadData() 调用时调用它 13 次。因此,如果您有 13 个单元格并且它加载了 13 个单元格,它将调用 willDisplay 并且您会得到一个误报,表明用户已到达底部。我相信...请有人确认
    【解决方案4】:

    在 Swift 4 中

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

    如果你实现了可扩展的UITableView/UICollectionView,你可能需要检查scrollView.contentSize.height &gt;= scrollView.frame.size.height

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 2020-09-24
      • 1970-01-01
      相关资源
      最近更新 更多