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

雨燕双飞 提交于 2019-11-29 18:37:30

问题


I have a tableView with many values.

I want to get the first indexPath.row value of the table which is being displayed currently.

How can I do that?

I get Following Error while implementing krishnabhadra's answer:

Line at which the error comes is:

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

ERROR:

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.'

What could be wrong?


回答1:


You can use tableView indexPathsForVisibleRows function, which returns an NSArray of NSIndexPath for all visible UITableViewCell. From indexPath.row you can find your array index.

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

indexPath.row will give you index of first object displayed.




回答2:


[self.myTableView visibleCells];

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

NSIndexPath *indexPath= [anArrayOfIndexPath lastObject];

Hope this will help you.




回答3:


you can use indexPathsForVisibleRows

Returns an array of index paths each identifying a visible row in the receiver.

- (NSArray *)indexPathsForVisibleRows

Return Value

An array of NSIndexPath objects each representing a row index and section index that together identify a visible row in the table view. Returns nil if no rows are visible.




回答4:


You can use: [self.tableView visibleCells]

That will return a nsarray of UITableViewCell objects, each representing a visible cell in the receiving table view.

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




回答5:


Get exact index number at center currently being displayed:

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

Example:

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

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

}


来源:https://stackoverflow.com/questions/5509571/how-to-get-indexpath-row-of-tableview-which-is-currently-being-displayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!