How to get UITableViewCell indexPath from the Cell?

后端 未结 11 1607
野趣味
野趣味 2020-12-07 20:11

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

相关标签:
11条回答
  • 2020-12-07 20:32
    1. Put a weak tableView property in cell's .h file like:

      @property (weak,nonatomic)UITableView *tableView;

    2. Assign the property in cellForRowAtIndex method like:

      cell.tableView = tableView;

    3. Now wherever you need the indexPath of cell:

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

    0 讨论(0)
  • 2020-12-07 20:37

    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.

    0 讨论(0)
  • 2020-12-07 20:39
    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.)

    0 讨论(0)
  • 2020-12-07 20:39

    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.

    0 讨论(0)
  • 2020-12-07 20:40

    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

    0 讨论(0)
提交回复
热议问题