How to find out the index row / row when clicking the button of the Tableview cell in UITableView?

I created a TableView with a custom UITableViewCell. The button is associated with each row of the table. Now I want to know the line number by pressing a button, so that I know which line button is pressed. I tried several things found on the stack, but nothing works.

I 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 also does not work.

Thanks for helping me.

+6
source share
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]; } 
+20
source

The best way to find out which tableView row is clicked is to set the value of the cell tag in the cellForRowAtIndexPath method when using a custom cell.

+1
source

Source: https://habr.com/ru/post/945314/


All Articles