Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which row/cell at center of the Screen in UITableView?

i have UITableview , many rows/cell in tableview.

when UITableview scrolling at that time , find which row/cell at center of the Screen.

like image 766
Mujahed Ansari Avatar asked Oct 18 '17 07:10

Mujahed Ansari


People also ask

How do you get the indexPath row when a button in a cell is tapped?

add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.

What does indexPath row return?

So to start with the indexPath. row will be 0. Then it will be 1, then 2, then 3 and so on. You do this so that you can get the correct string from the array each time.


2 Answers

There are a couple of options for getting the central row. One would be to get the indexPath at the centre:

NSIndexPath *indexPathAtCenter = [self.tableView indexPathForRowAtPoint:CGPointMake(self.tableView.bounds.size.width/2, self.tableView.bounds.size.height/2)];
UITableViewCell *centerCell = [self.tableView cellForRowAtIndexPath:indexPathAtCenter];

Alternatively you could get all visible indexPaths and choose the middle one:

NSArray<NSIndexPath*> *visibleIndexPaths = [self.tableView indexPathsForVisibleRows];
NSIndexPath *middleIndexPath = visibleIndexPaths[visibleIndexPaths.count/2];
UITableViewCell *centerCell = [self.tableView cellForRowAtIndexPath: middleIndexPath];

Depends on the rest of your implementation which route you want to go!

like image 159
Mike Atkins-Spelling Avatar answered Oct 03 '22 14:10

Mike Atkins-Spelling


In Swift 4

For exact index number at center we can simply use:-

let middleIndex = ((heightTableView.indexPathsForVisibleRows?.first?.row)! + (heightTableView.indexPathsForVisibleRows?.last?.row)!)/2
like image 43
piyush ranjan Avatar answered Oct 03 '22 16:10

piyush ranjan