【问题标题】:Detect the current top cell in a UITableView after scrolling滚动后检测 UITableView 中的当前顶部单元格
【发布时间】:2012-01-05 18:22:10
【问题描述】:

一个简单的问题,但我似乎没有正确的术语来搜索 Stackoverflow。

我有一个没有部分的 UITableView,用户可以在这个 tableview 中上下滚动一长串数据(行)。

问题:如何在用户滚动后检测到最顶部的单元格行号。 (例如,如果用户向下滚动 30 个单元格,则滚动后的顶部单元格 = 30)

【问题讨论】:

    标签: iphone objective-c cocoa-touch ipad uitableview


    【解决方案1】:

    您可以尝试使用UITableView-indexPathsForVisibleRows-indexPathForRowAtPoint

    例如,假设您要在停止拖动表格时打印最顶部可见单元格的 indexPath。你可以这样做:

    - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
        NSIndexPath *firstVisibleIndexPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:0];
        NSLog(@"first visible cell's section: %i, row: %i", firstVisibleIndexPath.section, firstVisibleIndexPath.row);
    }
    

    对于 Swift 3.0

    let topVisibleIndexPath:IndexPath = self.tableView.indexPathsForVisibleRows![0]
    

    【讨论】:

    • 我会对数组进行排序,因为文档中没有任何内容(据我所见)说索引路径按升序排序。
    • 这是一个不同的问题,但请查看tableView scrollToRowAtIndexPath
    • 当心,[self.tableView indexPathsForVisibleRows] 可能是空的,当用户滚动一个启用了弹跳的表格视图时,就像小鸡的速度一样。所以一定要检查该方法是否至少返回了 1 个索引路径。
    【解决方案2】:

    你得到可见行的索引路径

    NSArray* indexPaths = [tableView indexPathsForVisibleRows];
    

    然后使用compare:排序

    NSArray* sortedIndexPaths = [indexPaths sortedArrayUsingSelector:@selector(compare:)];
    

    然后获取第一个元素所在的行

    NSInteger row = [(NSIndexPath*)[sortedIndexPaths objectAtIndex:0] row];
    

    【讨论】:

    • 此解决方案适用于 UICollectionViews 和 UITableViews
    【解决方案3】:

    这是 Swift 3+ 代码:

    override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        let firstVisibleIndexPath = self.tableView.indexPathsForVisibleRows?[0]
        print("First visible cell section=\(firstVisibleIndexPath?.section), and row=\(firstVisibleIndexPath?.row)")
    }
    

    【讨论】:

      【解决方案4】:

      在 Swift 4 中:

      func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
          let firstVisibleIndexPath = self.tableview.indexPathsForVisibleRows?[0]
          print("top visible cell section  is \([firstVisibleIndexPath!.section])")
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-22
        • 1970-01-01
        • 1970-01-01
        • 2015-07-18
        • 2014-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多