使用下面的代码尝试一下..
- (void) buttonPressed: (id) sender withEvent: (UIEvent *) event
{
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)button.superview;
UITableView *tableView = (UITableView *)cell.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSLog(@"%d", indexPath.row);
}
或者
UIButton *button = (UIButton *)sender;
CGRect buttonFrame = [button convertRect:button.bounds toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonFrame.origin];
或
以编程方式在单元格中添加自定义按钮的整个示例
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
.......
cell.textLabel.text = [NSString stringWithFormat:@"Cell #%i", indexPath.row + 1];
//Create the button and add it to the cell
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Custom Action" forState:UIControlStateNormal];
button.frame = CGRectMake(150.0f, 5.0f, 150.0f, 30.0f);
[cell addSubview:button];
return cell;
}
并使用以下代码获取索引路径...
//Get the superview from this button which will be our cell
UITableViewCell *tblCell = (UITableViewCell*)[sender superview];
//From the cell get its index path.
NSIndexPath *indexPathE = [myTableView indexPathForCell:tblCell];
NSLog(@"%d", indexPathE.row);