2012-09-04 38 views
1

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

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

回答

3

试试下面的代码片段:

在的cellForRowAtIndexPath方法。设置indexpath.row作为按钮标签

[cellButton addTarget:自动作:@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. 
} 

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

如果你只需要改变按钮的图像上点击event.then我想,你不需要为indexpath或细胞。

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

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

好的,NSLog(cell)给了我Null。所以我有空单元格。也许我很笨,但我不明白我们创建新单元格和改变NEW单元格不存在的图像? – pash3r

+0

这里,“cellForRowAtIndexPath”方法将在选定的indexpath处返回引用单元格,我们只是在“cell”变量中引用相同的单元格。它不会创建新的单元格。 请检查self.tableView和CustomTableViewCell的存在。如果找不到,则创建名称为“tableView”的引用变量并将其与UI连接。对于“CustomTableViewCell”将其替换为您创建的自定义单元格对象,或使用“UITableViewCell”对象。 – Yajushi

+0

如果您使用Group tableView。那么你还需要检查正确的部分号码。 – Yajushi

-1

您可以将当前单元格的行分配为UIButton的标记。在您的目标/动作上,您可以检查按钮的标签以查找其按下的行。

+0

请写下示例代码。我不太明白你的意思。 – pash3r

+0

检查UIView文档。在UIView实例及其子类上有一个名为“tag”的属性。在你的 - tableView:cellForRowAtIndexPath:你可以将indexPath.row值分配给UIButton实例的标签属性。 – J2theC

+0

http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html – J2theC

0

你也应该能够得到indexPath:

NSIndexPath *indexPathForButton = [self.tableView indexPathForSelectedRow]; 

在您的.h文件,添加:

@property (nonatomic, retain) NSIndexPath* indexPathForButton; 

,改变indexPath,只要它的使用。 (self.indexPathForButton = indexPath;)

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

+0

它返回null! o_O – pash3r