Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass UITableView IndexPath to UIButton @selector by parameters in iOS?

I have added UIButton in UITableViewCells. I have when the user clicks the button we have get the indexpath to use the values from NSMutableArray. I have used the below to get the current IndexPath,

[getMeButton addTarget:self action:@selector(resendTheErrorMessage:) forControlEvents:UIControlEventTouchUpInside];

-(void) resendTheErrorMessage:(id)sender 
{
   NSLog(@"SEnder: %@", sender);
   //NSLog(@"Index Path : %@", indexpath);
}

Can anyone please help me to pass current indexpath UIButton's @selector. Thanks in advance.

EDIT:

This is the output I got from NSLog()

<UIButton: 0x864d420; frame = (225 31; 95 16); opaque = NO; tag = 105; layer = <CALayer: 0x864d570>>
like image 879
Yuvaraj.M Avatar asked Aug 13 '12 14:08

Yuvaraj.M


1 Answers

Add Your UIButton Like this

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setFrame:CGRectMake(10.0, 2.0, 140.0, 40.0)];
[btn setTitle:@"ButtonTitle" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[btn setTag:indexPath.row];
[cell.contentView addSubview:btn];

And then get its tag number -

-(void)buttonClicked:(id)sender
{
    NSLog(@"tag number is = %d",[sender tag]);
    //In this case the tag number of button will be same as your cellIndex.
   // You can make your cell from this.

   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[sender tag] inSection:0];
   UITableViewCell *cell = [tblView cellForRowAtIndexPath:indexPath];
}

Note: Above solution will work when your tableView has only 1 section. If your tableView has more than one section either you should know your section index or go for below methods.

Alternative:1

UIView *contentView = (UIView *)[sender superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [tblView indexPathForCell:cell];

Alternative:2

CGPoint touchPoint = [sender convertPoint:CGPointZero toView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint:touchPoint];
UITableViewCell *cell = [tblView cellForRowAtIndexPath:indexPath];
like image 106
TheTiger Avatar answered Oct 09 '22 13:10

TheTiger