2012-07-23 132 views
0

我在UITableView的每個單元格中都有一個按鈕。現在我想每個按鈕綁定到其操作方法在功能:如何在循環中設置UIButtons的動作?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ...} 

這裏是我試圖代碼:

NSString* functionNamePrefix = @"actionMethod_"; 
    NSString* functionName = [functionNamePrefix stringByAppendingString:[NSString stringWithFormat:@"%d",indexPath.row]]; 
    SEL selectorFromString = NSSelectorFromString(functionName); 
    [button addTarget:self action:@selector(selectorFromString:) forControlEvents:UIControlEventTouchDown]; 

失敗是:行動選擇採取「selectorFromString」作爲一個函數的名字,但SEL我從字符串轉換。

有什麼建議嗎? TIA!

回答

2

更好的方法是將所有按鈕分配給相同的操作,並在操作方法中確定按下按鈕時所在的行。否則,如果你的單元格被重用,每個按鈕都會有多個動作分配給它,這會很混亂。

您可以使用我對this question的回答輕鬆確定按鈕或其他控件所在的行。

1

你應該selectorFromString傳遞給動作參數,而不是@selector(selectorFromString :)

NSString* functionNamePrefix = @"actionMethod_"; 
NSString* functionName = [functionNamePrefix stringByAppendingString:[NSString stringWithFormat:@"%d",indexPath.row]]; 
SEL selectorFromString = NSSelectorFromString(functionName); 
[button addTarget:self action:selectorFromString forControlEvents:UIControlEventTouchDown]; 
+0

感謝,它works.But @jrturton的答案是做我想做的正確途徑。 – Maadiah 2012-07-24 02:04:51

0

如果你想使用SEL selectorFromString作爲選擇你的按鈕,你應該改變@selector(selectorFromString:)selectorFromString

0

嘗試這種方式,因爲你已經做出選擇你準備使用:

[button addTarget:self action:selectorFromString forControlEvents:UIControlEventTouchDown]; 
0

試試這種方法。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ...}

[button setTag:indexPath.row]; 
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchDown]; 

buttonTapped

-(void)buttonTapped:(UIButton *)button{ 

    switch(button.tag){ 
    //Your code here 
    } 
}