tags:

views:

269

answers:

6

Hi. I created a tableViewCell the include an image, two text labels and a uibutton. The button is allocated to an action method (e.g. viewButtonPused:sender).

I'm used to handle row selection with tableView:didSelectRowAtIndexPath: so I could tell which row was selected. But with the uibutton and its action method .... How can I tell?

Thanks in advance.

A: 

define one class variable int SelectedRow; inside didSelectRowAtIndexPath assign value to it like SelectedRow = indexPath.row;

use this SelectedRow variable in side your action method viewButtonPused:sender

mihirpmehta
Thanks, but didSelectRowAtIndexPath is not called unless I touch the row and not just the button.
Tzur Gazit
A: 

Instead of adding the button as a subview of the cell set it to be cell.accessoryView. Then use tableView:accessoryButtonTappedForRowWithIndexPath: to do your stuff that should be done when a user taps this button.

bddckr
Sounds interesting. I've already used the 'Tag' solution by now.I'll try this one next time.Many thanks.
Tzur Gazit
+2  A: 

when you set up each UITableViewCell in the cellForRowAtIndexPath: method assign a int to the button.tag propery that corrisponds to the row its on. That way when the viewButtonPused:sender is called you can do:

viewButtonPused:sender {

    UIButton *button = (UIButton *)sender;
    //check button.tag to see which row this button was.

}
jamone
Thanks. This answer was very helpful.
Tzur Gazit
+2  A: 

If the button's target is the UIViewController/UITableViewController or any other object that maintains a reference to the UITableView instance, this will do nicely:

- (void)viewButtonPushed:(id)sender {
    UIButton *button = (UIButton *)sender;
    UITableViewCell *cell = button.superview; // adjust according to your UITableViewCell-subclass' view hierarchy
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    // use your NSIndexPath here
}

Using this approach will let you avoid extra instance variables and will work fine in case you have multiple sections. You need to have a way to access the UITableView instance though.

Alexander Repty
Oh I like that way much better then using tags.
jamone
A: 

Another way that I use now is to subclass UIButton and add a property of type NSIndexPath. On cellForRowAtIndexPath I assign the value of indexPath and its available at the action method.

Tzur Gazit
A: 

Tzue Gazit

Can you provide any code on how you achieved this. Mainly the Tag Solution.

Thank you