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 t
Put a weak tableView property in cell's .h file like:
@property (weak,nonatomic)UITableView *tableView;
Assign the property in cellForRowAtIndex method like:
cell.tableView = tableView;
Now wherever you need the indexPath of cell:
NSIndexPath *indexPath = [cell.tableView indexPathForCell:cell];
Try with this from your UITableViewCell:
NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];
EDIT: Seems this doesn't work on iOS 8.1.2 and further. Thanks to Chris Prince for pointing it.
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.)
Swift 4.x
To provide access to my cell, i did something like this:
I have an extension of the UIView:
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
And then.. in my cell Class:
class SomeCell: UITableViewCell {
func someMethod() {
if let myViewController = self.parentViewController as? CarteleraTableViewController {
let indexPath : IndexPath = (myViewController.tableView).indexPath(for: self)!
print(indexPath)
}
}
}
Thats all form me.
Best regards.
You can try this simple tip:
on your UITableViewCell
Class :
@property NSInteger myCellIndex; //or add directly your indexPath
and on your cellForRowAtIndexPath
method :
...
[cell setMyCellIndex : indexPath.row]
now, you can retrieve your cell index anywhere