3

I have a UIButton inside my custom cell and I want to trigger an action when the user presses that button BUT I need to know from which row the UIButton was pressed.

Here is my code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;

    ...

    [button addTarget:self action:@selector(buttonPressedAction:)forControlEvents:UIControlEventTouchUpInside];

}

- (void)buttonPressedAction:(UIButton *)button
{
    //int row = indexPath.row;
    //NSLog(@"ROW: %i",row);
}

How do I pass the indexPath as argument to my selector?

P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
Pupillam
  • 631
  • 6
  • 26

4 Answers4

6

You can either set the tag property of the button to the row number:

button.tag = indexPath.row;

and retrieve it using

NSInteger row = button.tag;

or set the index path object itself as an associated object to the button:

objc_setAssociatedObject(button, "IndexPath", indexPath);

and

NSIndexPath *ip = objc_getAssociatedObject(button, "IndexPath");
2

while adding the button on the custom cell, u can add the tag property of UIButton as

UIButton *sampleButton = [[UIButton alloc] init];
sampleButton.tag = indexPath.row;

and then when u call, u can check the tag

- (void)buttonPressedAction:(UIButton*)sender
{
    if(sender.tag==0)
    {
      //perform action
    }
}

hope it helps. happy coding :)

Anshuk Garg
  • 1,540
  • 12
  • 14
  • You have to declare the button as UIButton, else the property accessor won't work. (I didn't -1, btw). –  Sep 06 '12 at 10:07
1

Simple set the button tag ..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;

    ...

    [button setTag = indexPath.row]; // Set button tag

    [button addTarget:self action:@selector(buttonPressedAction:)
                                            forControlEvents:UIControlEventTouchUpInside];
    }

    - (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        int row = [button superview].tag;
    }
}
P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
Vikas S Singh
  • 1,748
  • 1
  • 14
  • 29
1

Its even simple than setting a tag. Try this..

To get The indexPath try the following code.

UIView *contentView = (UIVIew *)[button superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];

OR

NSIndexPath *indexPath = [self.tableview indexPathForCell:(UITableViewCell *)[(UIVIew *)[button superview] superview]];
Sasi
  • 1,666
  • 2
  • 24
  • 44