Custom button in UITableViewCell - indexPath

Posted on 9 December 2008 by mike

Hi all

I am currently working on iPhone app number two when I came across a problem that it has taken me a while to sort out.  I wanted to place a button inside each UITableCell I am displaying.  I then wanted to call a method when the user pressed that button which would perform some action on the information related to the contents of that cell.

For this to be useful I needed to be able to get the indexpath of the row in which the button was pressed.  It took me a while to work this out but I eventually came up with a solution which is really simple, in fact so simple I am angry I did not work it out sooner. Below is the line of code I am using in my button method to get the indexPath.


NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];

The method signature used was:


- (void)buttonMethod:(UIButton *)sender


From this point on I was then able to access the section and row of the cell in which the button was pressed using:


NSInteger section = indexPath.section;
NSInteger row = indexPath.row;


Mike

blog comments powered by Disqus