2012-09-04 53 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