Detect the current top cell in a UITableView after scrolling

前端 未结 4 855
迷失自我
迷失自我 2020-12-04 17:01

a simple question but I don\'t seem to have the right terminology to search Stackoverflow by it.

I have a UITableView with no sections, the user can scroll up and do

相关标签:
4条回答
  • 2020-12-04 17:09

    You could try using UITableView's -indexPathsForVisibleRows or -indexPathForRowAtPoint.

    For example, let's say that you want to print the indexPath of the topmost visible cell, when you stop dragging your table. You could do something like this:

    - (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);
    }
    

    For Swift 3.0

    let topVisibleIndexPath:IndexPath = self.tableView.indexPathsForVisibleRows![0]
    
    0 讨论(0)
  • 2020-12-04 17:12

    In 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])")
    }
    
    0 讨论(0)
  • 2020-12-04 17:16

    This is the Swift 3+ code:

    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)")
    }
    
    0 讨论(0)
  • 2020-12-04 17:22

    You get the index paths for the visible rows

    NSArray* indexPaths = [tableView indexPathsForVisibleRows];
    

    Then sort using compare:

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

    Then get the first element's row

    NSInteger row = [(NSIndexPath*)[sortedIndexPaths objectAtIndex:0] row];
    
    0 讨论(0)
提交回复
热议问题