一个简单的问题,但我似乎没有正确的术语来搜索Stackoverflow。
我有一个没有任何部分的UITableView,用户可以向上和向下滚动此tableview中显示的一长串数据(行)。
问题:如何在用户滚动后检测最顶部的单元格行号。 (例如,如果用户向下滚动30个单元格,则滚动后的顶部单元格= 30)
答案 0 :(得分:70)
您可以尝试使用UITableView
的{{1}}或-indexPathsForVisibleRows
。
例如,假设您要停止拖动表格时打印最顶层可见单元格的indexPath。你可以这样做:
-indexPathForRowAtPoint
对于Swift 3.0
- (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);
}
答案 1 :(得分:31)
您获得可见行的索引路径
NSArray* indexPaths = [tableView indexPathsForVisibleRows];
然后使用compare:
NSArray* sortedIndexPaths = [indexPaths sortedArrayUsingSelector:@selector(compare:)];
然后获取第一个元素的行
NSInteger row = [(NSIndexPath*)[sortedIndexPaths objectAtIndex:0] row];
答案 2 :(得分:8)
这是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)")
}
答案 3 :(得分:0)
在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])")
}