2012-07-23 138 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 
    } 
}