Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get UITableViewCell indexPath from the Cell?

How do I, from a cell, get its indexPath in a UITableView?

I've searched around stack overflow and google, but all the information is on the other way around. Is there some way to access the superView/UITableView and then search for the cell?

More information about the context: there are two classes that I have, one is called Cue and one is called CueTableCell (which is a subclass of UITableViewCell) CueTableCell is the visual representation of Cue (both classes have pointers to each other). Cue objects are in a linked list and when the user performs a certain command, the visual representation (the CueTableCell) of the next Cue needs to be selected. So the Cue class calls the select method on the next Cue in the list, which retrieves the UITableView from the cell and calls its selectRowAtIndexPath:animated:scrollPosition:, for which it needs the indexPath of the UITableViewCell.

like image 580
sinθ Avatar asked Mar 29 '13 21:03

sinθ


People also ask

How do I get IndexPath from cell Swift?

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.

How do I get last IndexPath in Swift?

You can get the indexPath of the last row in last section like this. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(numberOfRowsInLastSection - 1) inSection:(numberOfSections - 1)];

How do I create an IndexPath in Objective C?

To create an IndexPath in objective C we can use. NSIndexPath *myIP = [NSIndexPath indexPathForRow: 5 inSection: 2] ; To create an IndexPath in Swift we can use.


1 Answers

NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 

It helps reading the UITableView documentation, even if this is by some regarded to be controversial (see comments below).

The cell has no business knowing what its index path is. The controller should contain any code that manipulates UI elements based on the data model or that modifies data based on UI interactions. (See MVC.)

like image 108
Mundi Avatar answered Oct 13 '22 04:10

Mundi