How to get indexPath.row of tableView which is currently being displayed?
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?
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.
[self.myTableView visibleCells];
NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[self.myTableView indexPathsForVisibleRows]];
NSIndexPath *indexPath= [anArrayOfIndexPath lastObject];
Hope this will help you.
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.
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
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)
}
精彩评论