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

时间:2011-04-01 05:40:37

标签: ios cocoa-touch uitableview ios4 nsarray

我有一个包含许多值的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.'

可能出现什么问题?

5 个答案:

答案 0 :(得分:23)

您可以使用tableView indexPathsForVisibleRows函数,该函数为所有可见的NSArray返回NSIndexPath UITableViewCellindexPath.row。从NSArray *visible = [tableView indexPathsForVisibleRows]; NSIndexPath *indexpath = (NSIndexPath*)[visible objectAtIndex:0]; 您可以找到您的数组索引。

indexPath.row

{{1}}将为您显示第一个对象的索引。

答案 1 :(得分:3)

[self.myTableView visibleCells];

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

NSIndexPath *indexPath= [anArrayOfIndexPath lastObject];

希望这会对你有所帮助。

答案 2 :(得分:3)

您可以使用indexPathsForVisibleRows

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

- (NSArray *)indexPathsForVisibleRows

返回值

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

答案 3 :(得分:0)

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

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

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

答案 4 :(得分:0)

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

 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)

}
相关问题