2016-01-27 36 views
0

什麼是最好的方法爲UITableViewCell中的UIButton添加和刪除目標操作。在UITableViewCell中爲UIButton添加和刪除目標操作

對於I中的每一行,將根據行索引具有不同的按鈕操作。顯示請告訴我在哪裏添加按鈕的添加目標並刪除按鈕的目標。

我在詢問要使用的委託和數據源。

+0

只需在添加表格單元按鈕並設置按鈕標籤作爲行的索引路徑時添加目標。現在在目標方法中接收此按鈕標籤並應用與按鈕標籤對應的操作。 –

+0

是的,它是簡單的實現,在我的實現中,我不會有相同的邏輯來使用索引路徑。行爲方法根據行索引而不同。 – Arasuvel

+0

然後在-cellForRowAtIndexPath:方法的按鈕操作中添加一個單一的函數,併爲選定的行索引獲取按鈕標記。並根據標籤執行操作(indexpath) –

回答

1

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [cell.btn1 removeTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside]; 
    [cell.btn1 removeTarget:self action:@selector(action2:) forControlEvents:UIControlEventTouchUpInside]; 

    cell.btn1.tag = indexPath.row; 

    if(indexPath.row%2) 
    { 
     [cell.btn1 addTarget:self action:@selector(onbtnWeighIn:) forControlEvents:UIControlEventTouchUpInside]; 
    } 
    else{ 
     [cell.btn1 addTarget:self action:@selector(onBtnViewTable:) forControlEvents:UIControlEventTouchUpInside]; 
    } 

} 
+0

謝謝。上述代碼的小更新[cell.btn1 removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside] ;.我只是做了上述,但是這是否是最好的方式? – Arasuvel

0

設置tag值在TableViewCell每個button並添加target也如下所示..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    cell.btn.tag = indexPath.row; 
    [btn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside]; 
    return cell; 
} 

現在添加一個選擇方法btnTapped如下所示。此方法每次調用tableview單元格中的每個按鈕單擊事件。

- (void)btnTapped:(UIButton *)sender { 
    UITableViewCell * cell = [[sender superview] superview]; 
    NSIndexPath * path = [self.tableView indexPathForCell:cell]; 
} 

在這裏,您有indexpath選定的按鈕,然後自定義您想要的。

0

從按鈕

[button removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents]; 

刪除所有動作的按鈕添加一個動作

[button addTarget:self action:@selector(action1Method) forControlEvents:UIControlEventTouchUpInside]; 

請注意,如果你從一個動作切換按鈕到另一個動作,由於狀態的變化,它很好地消除這些行爲。否則,即使您爲該表重新裝入數據,所有操作也會顯示出來。

相關問題