如何获取当前正在显示的tableView的indexPath.row?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何获取当前正在显示的tableView的indexPath.row?相关的知识,希望对你有一定的参考价值。

我有一个包含许多值的tableView。

我想得到当前显示的表的第一个indexPath.row值。

我怎样才能做到这一点?

我在实现krishnabhadra的答案时得到以下错误:

出现错误的行是:

[self.table scrollToRowAtIndexPath:indexVis atScrollPosition:UITableViewScrollPositionTop animated:YES];

错误:

Assertion failure in -[NSIndexPath row], /SourceCache/UIKit_Sim/UIKit-1447.6.4/UITableViewSupport.m:2018
2011-04-01 11:57:25.458 GlossaryPro[1525:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid index path for use with UITableView.  Index paths passed to table view must contain exactly two indices specifying the section and row.  Please use the category on NSIndexPath in UITableView.h if possible.'

可能有什么不对?

答案

你可以使用tableView indexPathsForVisibleRows函数,它为所有可见的NSArray返回NSIndexPathUITableViewCell。从indexPath.row你可以找到你的数组索引。

NSArray *visible       = [tableView indexPathsForVisibleRows];
NSIndexPath *indexpath = (NSIndexPath*)[visible objectAtIndex:0];

indexPath.row将为您显示第一个对象的索引。

另一答案
[self.myTableView visibleCells];

NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[self.myTableView indexPathsForVisibleRows]];

NSIndexPath *indexPath= [anArrayOfIndexPath lastObject];

希望这会帮助你。

另一答案

你可以使用indexPathsForVisibleRows

返回索引路径数组,每个索引路径标识接收器中的可见行。

- (NSArray *)indexPathsForVisibleRows

回报价值

NSIndexPath对象的数组,每个对象表示行索引和段索引,它们一起标识表视图中的可见行。如果没有可见的行,则返回nil。

另一答案

你可以使用:[self.tableView visibleCells]

这将返回一个UARableViewCell对象的数组,每个对象代表接收表视图中的一个可见单元格。

http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITableView_Class/Reference/Reference.html

另一答案

获取当前正在显示的中心的确切索引号:

 let middleIndex = ((tableView.indexPathsForVisibleRows?.first?.row)! + (tableView.indexPathsForVisibleRows?.last?.row)!)/2

例:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

  let middleIndex = ((tableView.indexPathsForVisibleRows?.first?.row)! + (tableView.indexPathsForVisibleRows?.last?.row)!)/2
  print(middleIndex)

}

以上是关于如何获取当前正在显示的tableView的indexPath.row?的主要内容,如果未能解决你的问题,请参考以下文章

如何获取tableview中当前选中的cell

如何使用 Swift 从 tableview 单元格中获取数据而不显示在标签上?

如何使用 Alamofire 4.0 获取 JSON 字典/数组并将其显示在 tableView Cell 上

获取 tableview insertRowsAtIndexPaths 以接受 indexOfObject?

如何过滤获取的数据并加载到 tableview 中?

ios在tableview单元格中显示/隐藏视图