0

Possible Duplicate:
Detecting which UIButton was pressed in a UITableView

I have a UIButton added to a UITableViewCell I want this button to call the "didSelectRowAtIndexPath" I already know about calling

  [self tableView:self.tableView didSelectRowAtIndexPath:indexpath];

but the problem that I can't get the indexpath and tried the

[self.Tableview indexPathForRowAtPoint:[self.view convertPoint:[sender center] fromView:self.Tableview]]

method but it returns the same CGPoint , Any help ?

Community
  • 1
  • 1
Mohamed Elzarei
  • 515
  • 3
  • 20

2 Answers2

4

First, you should not directly call didSelectRowAtIndexPath yourself. It is a delegate method, and the table view should call it.

Instead, make a separate method to do what you want to do, and call that from didSelectRowAtIndexPath.

Second, you can get the index path like this:

UIButton* button = (UIButton*) sender;
UITableViewCell *cell = (UITableViewCell*)button.superview.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

This works because if everything is set up the standard way, the superview of the button should be the cell's contentView, and that should be a subview of the cell.

Mundi
  • 79,884
  • 17
  • 117
  • 140
0

Best way to do according to me is give ROW NUMBER AS TAG VALUE FOR tableViewCell' button, so when you click button its action will be called from which you will get the sender id sender_id is nothing but UIButton instance, fetch its tag value..

eg: You have UIButton *testButton;
Its Selector is @selector (testButtonPressed:)

So when tableViewCell's Button is pressed it will call @selector (testButtonPressed:)

-(void)testButtonPressed:(id)sender
 {
     NSLog(@"index is %d", sender. tag);
 }
Ashwin Kumar
  • 622
  • 4
  • 7
  • This is not very scalable e.g. it only works for one section. – Paul.s Aug 14 '12 at 11:44
  • @Paul.s Yes, but you could set up a scheme like `tag = section*1000+row`. – Mundi Aug 14 '12 at 14:42
  • @Mundi I just generally am not fond of the `tag` property there are better ways of doing things - like your answer for example – Paul.s Aug 14 '12 at 14:44
  • i think its scalable... coz tag is being set when u create cells.... this logic can improved... by having custom button (meant to say inherit button class) and have variable of type NSObject which can be used as tag.... so using this method we can even send tag object as paramter for actions – Ashwin Kumar Aug 21 '12 at 05:51