Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting row of UITableView cell on button press

I have a tableview controller that displays a row of cells. Each cell has 3 buttons. I have numbered the tags for each cell to be 1,2,3. The problem is I don't know how to find on which cell a button is being pressed. I'm currently only getting the sender's tag when one of the buttons has been pressed. Is there a way to get the cell row number as well when a button is pressed?

like image 778
minimalpop Avatar asked Sep 21 '11 18:09

minimalpop


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.

How can we use a reusable cell in UITableView?

For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.


2 Answers

You should really be using this method instead:

CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView]; NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition]; 

Swift version:

let buttonPosition = sender.convert(CGPoint(), to:tableView) let indexPath = tableView.indexPathForRow(at:buttonPosition) 

That will give you the indexPath based on the position of the button that was pressed. Then you'd just call cellForRowAtIndexPath if you need the cell or indexPath.row if you need the row number.

If you're paranoid, you can check for if (indexPath) ... before using it just in case the indexPath isn't found for that point on the table view.

All of the other answers are likely to break if Apple decides to change the view structure.

like image 190
iwasrobbed Avatar answered Sep 19 '22 16:09

iwasrobbed


Edit: This answer is outdated. Please use this method instead


Try this:

-(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); } 

Edit: If you are using contentView, use this for buttonCell instead:

UITableViewCell *buttonCell = (UITableViewCell *)senderButton.superview.superview; 
like image 28
user523234 Avatar answered Sep 17 '22 16:09

user523234