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. The above solution will work if there is only 1 section in the TableView table. If your tableView has more than one section, you should know your section index or go below.
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];
TheTiger
source share