Custom UITableViewCell and IBAction

Yogesh picture Yogesh · Nov 5, 2010 · Viewed 14.1k times · Source

I have a custom UITableViewCell on which I have added a button, I have associated that button on an IBAction in my viewController. Now the problem that i am facing is how do I know from which cell that button was created. When I present my viewController which has a table in it and has multiple rows (custom UITableViewCell), now when the user presses the button the action is getting called, but how do I know which row was it.

Because based on the row index I need to store some value.

Edit: I have some clue on it now, but still I am not sure how will I do it, so it seems like on my tableViewController cellForRowAtIndexPath method I have to do something like this

[cell.button1 addTarget:self action:@selector(addToCart:) forControlEvents:UIControlEventTouchUpInside];

And then I have to write a method

-(IBAction) addToCart:(id) sender

But still what I don't know is how do i get the row index in my addToCart method. Appreciate your help.

Answer

Yogesh picture Yogesh · Nov 8, 2010

Ok, finally I got the answer, looking into different forums, people were suggesting to do something like this

in the custom table view controller in cellForRowAtIndexPath do this

cell.addToCart.tag = indexPath.row;
[cell.addToCart addTarget:self action:@selector(addToCart:)    
                               forControlEvents:UIControlEventTouchUpInside];

where addToCart is name of UIButton in my customUITableViewCell. It didn't seems to work for me. So this is what I did

-(IBAction) addToCart:(id) sender{
        NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)
                    [[sender superview] superview]];
    NSLog(@"The row id is %d",  indexPath.row); 
 }

And then through interfacebuilder I associated the action of my button to addToCart IBAction on my table view controller.