繁体   English   中英

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

[英]How to get indexPath.row of tableView which is currently being displayed?

我有一个包含许多值的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函数,该函数为所有可见的UITableViewCell返回NSIndexPathNSArray 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)

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM