Search code examples
iosobjective-cuitableviewseguensindexpath

How to get indexPath of a custom cell in PrepareForSegue method - iOS


I have a custom cell with few views and buttons in it. From 1 of the buttons, I'm performing a Segue and I need that cell number but no idea how to get it. Please help.

Heres how my cell looks:

enter image description here

the prepareForSegue is called from the red circled button.

Here's the code:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _array.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NewsFeedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsFeedCell" forIndexPath:indexPath];
    if (cell) {
        cell.item = _array[indexPath.section];
    }

    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"AudioComment"])
    {
      NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        NSLog(@"%ld",(long)indexPath.section); //printing 0 everytime :(
    }
}

Please provide any help/suggestions on how can i get the indexPath?

Thanks.


Solution

  • You have to set tag on the button. In your case, set the button tag as indexPath.section in CellforRowAtIndexPath.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        NewsFeedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsFeedCell" forIndexPath:indexPath];
        if (cell) {
            cell.item = _array[indexPath.section];
        }
    
        cell.button1.tag = indexPath.section;
        return cell;
    }
    

    In PrepareForSegue, get the index from button tag.

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
        if ([segue.identifier isEqualToString:@"AudioComment"])
        {
            NSInteger index = ((UIButton *) sender).tag;
            NSLog(@" %ld ",index);
        }
    }