Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get indexPath over touched button?

I've got dynamic tableView and one problem. In each tableCell are two buttons. I'm trying to get indexPath.row on button touched but with no success.

My code:

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

    NSIndexPath *indexPath = [self.homeTableView indexPathForSelectedRow];      

    NSLog(@"%d", indexPath.row);


}

How can I get indexPath.row for touced button (Segue connections are over this two buttons->two connections)?

like image 492
iWizard Avatar asked Nov 27 '22 17:11

iWizard


2 Answers

It's not working because you do not select row when you click button.

With two buttons I would disconnect your segues from buttons and do 2 manual segues in IB then add code like that to handle them:

-(void)button1Pressed:(id)sender {
    UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath *clickedButtonIndexPath = [self.homeTableView indexPathForCell:clickedCell];
    ...
    [self performSegueWithIdentifier:@"YourManualSegueIdentifier1" sender:self];
}

Edit for second option:

In your MyTableViewCell.h:

@interface MyTableViewCell : UITableViewCell
    ...    
    @property (strong, nonatomic) NSIndexPath *cellIndexPath;
    ...
@end

In your MyTableViewCell.m:

-(void)button1Pressed:(id)sender {
    ...
    NSInteger row = cellIndexPath.row;
    ...
}

In your MyTableViewController.m:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];      
    }
    // remember index here!
    [cell setCellIndexPath:indexPath];
    ....
    return cell;
}
like image 65
Tomasz Zabłocki Avatar answered Dec 05 '22 15:12

Tomasz Zabłocki


Apple change the UITableViewCell hierarchy in iOS 7

Using iOS 6.1 SDK

<UITableViewCell>
   | <UITableViewCellContentView>
   |    | <UILabel>

Using iOS 7 SDK

<UITableViewCell>
   | <UITableViewCellScrollView>
   |    | <UITableViewCellContentView>
   |    |    | <UILabel>

So if you want to get indexpath at button index then use following code Using iOS 6 or later SDK

UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath *clickedButtonPath = [book_table indexPathForCell:clickedCell];
    NSLog(@"index=%@",clickedButtonPath);

Using iOS 7 or 7+ SDK

 UITableViewCell *clickedCell = (UITableViewCell *)[[[sender superview] superview]superview];
    NSIndexPath *clickedButtonPath = [book_table indexPathForCell:clickedCell];
    NSLog(@"index=%ld",(long)clickedButtonPath.item);
like image 26
Bhoopi Avatar answered Dec 05 '22 14:12

Bhoopi