Flipkart Search

Search This Blog

Tuesday, May 12, 2009

Custom button in UITableViewCell - indexPath



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.tblView indexPathForCell:(UITableViewCell *)[sender 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;

//for getting cell
UITableViewCell *retcell = (UITableViewCell *)[sender superview];

for deleting cell
switch(indexPath.row){
case 0:
[retcell removeFromSuperview];
break;
case 1:
[retcell removeFromSuperview];
break;
default:
break;

8 comments:

Unknown said...

Thanks! Just what I was looking for.

Anonymous said...

Dude, that plagiarism is sad: http://www.71squared.com/2008/12/custom-button-in-uitableviewcell-indexpath/

SMVEN said...

your code is not working ... any help....when we change image of button after selection,
it works..but if i scroll tableview , it goes to previous image....it did not show new image.......

Rahul Vyas said...

@SMVEN-set the background image of button for all states(normal,selected,highlighted,disabled) when we scrolls table viwe it redrwas cells that's why you are getting problem.

Anonymous said...

LOL Anonymous!!!! You can always count on a hindu to rip off something and pass it off as their own. Stupid cow pissing dot head.

Anonymous said...

In my case [[sender superview] superview] work. But [sender superview] return UTTableCellContentView

Hiệp Lê tuấn said...

Thanks, with me it works with [[sender superview] superview] :)

Anonymous said...

Great post, very useful. Thanks for this.

But for me also - [[sender superview] superview] made the difference.