Pupillam
Pupillam

Reputation: 641

Pass an argument to selector

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?

Upvotes: 3

Views: 1225

Answers (4)

Vikas S Singh
Vikas S Singh

Reputation: 1766

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;
    }
}

Upvotes: 1

Sasi
Sasi

Reputation: 1897

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]];

Upvotes: 1

Anshuk Garg
Anshuk Garg

Reputation: 1540

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 :)

Upvotes: 2

user529758
user529758

Reputation:

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");

Upvotes: 6

Related Questions