如何按下按钮确定行?

时间:2012-09-04 15:49:22

标签: iphone uitableview uibutton nsindexpath

我有我的自定义uitableviewcell。它有uibutton,uibutton与行动。那么如何知道按下uibutton的行的indexPath?

目标:每行上的uibuttons都有一个图像。因此,当用户点击按钮时,它会显示警报视图,如果答案为“是”,则uibutton的图像会发生变化。

3 个答案:

答案 0 :(得分:3)

尝试以下代码段:

在cellForRowAtIndexPath方法中。将indexpath.row设置为按钮标记

  

[cellButton addTarget:self action:@selector(cellBottonClicked :)   forControlEvents:UIControlEventTouchUpInside];
    cellButton.tag = indexPath.row;

-(IBAction) cellBottonClicked:(id)sender{
    NSInteger row = [sender tag];
    //you can get indexpath from row
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0]; 
    CustomTableViewCell *cell = (CustomTableViewCell *)[self.tableView  cellForRowAtIndexPath:indexPath];
    // from this cell you can fetch and change image of selected cell's button. 
}

[编辑:仅更改按钮的图像]

如果您只需要在点击事件上更改按钮图像。那么我认为您不需要索引路径或单元格。

试试这段代码。希望它会有所帮助:

-(IBAction) cellBottonClicked:(id)sender{
   UIButton *btn = (UIButton *)sender;
   [btn setImage:yourImage forState:UIControlStateNormal];
 }

答案 1 :(得分:0)

您还应该能够通过以下方式获取indexPath:

NSIndexPath *indexPathForButton = [self.tableView indexPathForSelectedRow];
在.h文件中

,添加:

@property (nonatomic, retain) NSIndexPath* indexPathForButton;

并在使用时更改indexPath。 (self.indexPathForButton = indexPath;)

但使用标签非常舒服......

答案 2 :(得分:-1)

您可以将当前单元格的行指定为UIButton的标记。在目标/操作上,您可以检查按钮的标记以找到按下它的行。