簡體   English   中英

滾動后檢測 UITableView 中的當前頂部單元格

[英]Detect the current top cell in a UITableView after scrolling

一個簡單的問題,但我似乎沒有正確的術語來搜索 Stackoverflow。

我有一個沒有部分的 UITableView,用戶可以上下滾動顯示在這個 tableview 中的一長串數據(行)。

問題:如何在用戶滾動后檢測最頂部的單元格行號。 (例如,如果用戶向下滾動 30 個單元格,則滾動后的頂部單元格為 = 30)

您可以嘗試使用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]

您獲得可見行的索引路徑

NSArray* indexPaths = [tableView indexPathsForVisibleRows];

然后使用compare:排序compare:

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

然后獲取第一個元素的行

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM