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?
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With