Yuvaraj.M Yuvaraj.M - 1 year ago 235
iOS Question

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

I have added

. I have when the user clicks the button we have get the indexpath to use the values from
. I have used the below to get the current

[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
@selector. Thanks in advance.


This is the output I got from

<UIButton: 0x864d420; frame = (225 31; 95 16); opaque = NO; tag = 105; layer = <CALayer: 0x864d570>>

Answer Source

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 -

    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.


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


CGPoint touchPoint = [sender convertPoint:CGPointZero toView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint:touchPoint];
UITableViewCell *cell = [tblView cellForRowAtIndexPath:indexPath];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download