Iphone 确定Tableview中每行的按钮选择?

Iphone 确定Tableview中每行的按钮选择?,iphone,Iphone,(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{ UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(230.0f, 4.0f, 60.0f, 36.0f); [btn setTitle:@"OK" forState:UIC

(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(230.0f, 4.0f, 60.0f, 36.0f);
[btn setTitle:@"OK" forState:UIControlStateNormal];
[btn setTitle:@"OK" forState:UIControlStateSelected];
[btn addTarget:self action:@selector(onClickRename:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn];

return cell;
}

但是,如果用户选择了特定行上的按钮,我可以通过onClickRename更改该图像……但是我可以得到哪一行的图像被触摸过吗

  • (void)tableView:(UITableView)tableView没有选择RowatineXpath:(NSIndexPath)indexPath
你可以做如下事情

[btn setTag:[indexPath] row]
在您的单元格设置中,然后

- (void) onClickRename:(id)sender {
    int row = sender.tag;
} 

您将知道命中了哪个表行。

苹果在其示例代码中使用了以下技术:

- (void)checkButtonTapped:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath != nil)
    {
        // do what you want with the item at indexPath
    }
}

在Swift中,可以为每个按钮设置标记

另外,将每个索引值设置为其标记,我们就可以知道在哪一行单击了哪个按钮

要设置标记,请在cellForAtIndexPath中

cell.button.tag = indexPath.row


in button Action

@IBAction func anAction(_sender : AnyObject){

 let tappedButton = sender.tag // gives the row and button

}