Search code examples
iosnsindexpath

How to call indexPath in another view?


I have two views listOptionTable.m(UITableViewController) and listOptionCell.m(UITableViewCell).

I'm trying to call the deselectRowAtIndexPath method in listOptionCell.m while I need to get indexPath so it can run.

Please how can I get the indexPath from listOptionTable.m?

listOptionCell.h

  listOptionTable *tableVC;

listOptionCell.m

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:NO];

    if (isSelected){

        [tableVC.tbl deselectRowAtIndexPath:`indexPath` animated:YES]; //I have to call indexPath in here.

    }
    else
    {
     ....
    }
}

Solution

  • I think the behaviour of your cell is strange. Anyway you can do that trick:

    1. Add property to your custom cell (listOptionCell.m):

      @property (strong, nonatomic) NSIndexPath *indexPath;
      
    2. Implement UITableViewDataSource method in listOptionTable.m like:

      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
      {
        listOptionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
        // Configure the cell...
        cell.indexPath = indexPath;
        return cell;
      }
      
    3. Now you can get indexPath in your cell:

      [tableVC.tbl deselectRowAtIndexPath:self.indexPath animated:YES];
      

    The better approach is to declare custom protocol in your cell and then ask delegate to deselect row at index path.