6

I created a TableView having a custom UITableViewCell. A button is associated with each row of tableview. Now I want to know the row number on click of a button, so that I would know that of which row button has been clicked. I have given a try to few things found on stack but nothing is working.

I have tried this code -:

-(void)button1Tapped:(id)sender
{
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];
UITableView* table = (UITableView *)[buttonCell superview];
NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell];
NSInteger rowOfTheCell = [pathOfTheCell row];
NSLog(@"rowofthecell %d", rowOfTheCell);
}

But this is also not working.

Thanks for helping me out.

Alex Bichel
  • 85
  • 1
  • 2
  • 5

2 Answers2

20

try with this

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            [[cell contentView] setBackgroundColor:[UIColor clearColor]];
            [[cell backgroundView] setBackgroundColor:[UIColor clearColor]];
             [cell.Mybutton addTarget:self action:@selector(btnCommentClick:) forControlEvents:UIControlEventTouchUpInside];
        }
         cell.Mybutton.tag=indexPath.row;
    }

    -(void)btnCommentClick:(id)sender
    {
            UIButton *senderButton = (UIButton *)sender;  
            NSLog(@"current Row=%d",senderButton.tag);
            NSIndexPath *path = [NSIndexPath indexPathForRow:senderButton.tag inSection:0];
    }
rptwsthi
  • 10,094
  • 10
  • 68
  • 109
SAMIR RATHOD
  • 3,512
  • 1
  • 20
  • 45
  • This doesn't work in case of nested table. when we have multiple sessions. – tumbudu Oct 03 '13 at 14:45
  • @SAMIRRATHOD sir if i have multiple tableview in one view and then how to know senderButton.tag return from which table ? – Rushi trivedi Nov 20 '14 at 07:01
  • @knocker, for multiple sections situation, use custom cell with a property NSIndexPath *indexPath would help, but be careful that one should make sure each custom cell's indexPath value is always up to date. For multiple tableview, give each tableview a tag then pass it to each cell respectively, just an idea, have not tried yet. – yuchen Jan 11 '17 at 03:47
1

The best way to know which row of tableView is clicked is by setting tag value of cell button in cellForRowAtIndexPath method while using custom cell.

Prince Kumar Sharma
  • 12,591
  • 4
  • 59
  • 90