Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the indexPath/row on button click of Tableview cell in a UITableView? [duplicate]

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.

like image 700
Alex Bichel Avatar asked May 18 '13 05:05

Alex Bichel


People also ask

How do you get the indexPath row when a button in a cell is tapped?

add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.

What is indexPath row?

A list of indexes that together represent the path to a specific location in a tree of nested arrays.

What is indexPath in tableView Swift?

indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.


2 Answers

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];
    }
like image 80
SAMIR RATHOD Avatar answered Nov 02 '22 23:11

SAMIR RATHOD


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.

like image 41
Prince Kumar Sharma Avatar answered Nov 02 '22 22:11

Prince Kumar Sharma