[英]Detect the current top cell in a UITableView after scrolling
a simple question but I don't seem to have the right terminology to search Stackoverflow by it.一个简单的问题,但我似乎没有正确的术语来搜索 Stackoverflow。
I have a UITableView with no sections, the user can scroll up and down a long list of data (rows) presented inside this tableview.我有一个没有部分的 UITableView,用户可以上下滚动显示在这个 tableview 中的一长串数据(行)。
Question: how can I detect the most top cell row number after the user scrolled.问题:如何在用户滚动后检测最顶部的单元格行号。 (for example, if the user is scrolling 30 cells down, the top cell after the scroll is = 30)
(例如,如果用户向下滚动 30 个单元格,则滚动后的顶部单元格为 = 30)
You could try using UITableView
's -indexPathsForVisibleRows
or -indexPathForRowAtPoint
.您可以尝试使用
UITableView
的-indexPathsForVisibleRows
或-indexPathForRowAtPoint
。
For example, let's say that you want to print the indexPath of the topmost visible cell, when you stop dragging your table.例如,假设您要在停止拖动表格时打印最顶部可见单元格的 indexPath。 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对于 Swift 3.0
let topVisibleIndexPath:IndexPath = self.tableView.indexPathsForVisibleRows![0]
You get the index paths for the visible rows您获得可见行的索引路径
NSArray* indexPaths = [tableView indexPathsForVisibleRows];
Then sort using compare:
然后使用
compare:
排序compare:
NSArray* sortedIndexPaths = [indexPaths sortedArrayUsingSelector:@selector(compare:)];
Then get the first element's row然后获取第一个元素的行
NSInteger row = [(NSIndexPath*)[sortedIndexPaths objectAtIndex:0] row];
This is the Swift 3+ code:这是 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)")
}
In Swift 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])")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.