-1

I have a UITableViewCell with a button inside it, when I press the button, it moves onto the next view, but I need to pass the index of the TableViewCell, but I cannot find this because it is NOT in DidSelectCellAtIndexPath, it is only the button that is pressable.

How do I find out the indexPath of the Button and why does it crash?

James Walker
  • 69
  • 1
  • 8

2 Answers2

0

A very Simple solution :-

(void)btnAction:(id)sender
  CGPoint btnRectPoint = [sender convertPoint:CGPointZero
                                   toView:self.tableView];
  NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:btnRectPoint]; // Here you can get your indexpath of table
NSLog(@"index.row=%d",indexPath);

}
Vizllx
  • 9,135
  • 1
  • 41
  • 79
  • this works and logs the index path, but then in prepareForSegue, if I try to pass the indexPath, to an IndexPath in ViewController2.h it crashes with "unrecognized selector sent to instance" – James Walker May 04 '15 at 12:35
  • my code in prepareForSegue is `-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { [super prepareForSegue:segue sender:sender]; ViewController2 *view = [segue destinationViewController]; view.indexPath = self.indexPath; }` – James Walker May 04 '15 at 12:36
  • it breaks on `view.indexPath = self.indexPath`. self.indexPath is assigned at the bottom of the -(void)btnAction:(id)sender – James Walker May 04 '15 at 12:59
  • inside (void)btnAction:(id)sender...... self.indexPath = indexPath; – James Walker May 04 '15 at 13:03
  • i have posted a code in separate question, will post link when it allows me to post the question. how do i initialized "self.indexPath" in ViewController2 – James Walker May 04 '15 at 13:14
  • Im in chat, you around? – James Walker May 04 '15 at 13:25
0

You can create a protocol and implement the delegate method in your UIViewController. Now when you are clicking on button inside UITableViewCell, you can pass the cell object itself as parameter to that delegate method.

-(void)protocolMethod:(id)sender {  
    [self.delegate delegateMethod:self];  
}

and in your UIViewController, you can get the index path of this cell from your table view.

-(void)delegateMethod:(MyCustomCell*)cell {
    NSIndexPath *indexPath = [self.objTableView indexPathForCell:cell];
}
Gandalf
  • 2,399
  • 2
  • 15
  • 19