Question
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?
Answer
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.