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
.
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.
You can get the indexPath of the last row in last section like this. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(numberOfRowsInLastSection - 1) inSection:(numberOfSections - 1)];
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With