应用程序在为动态按钮分配多个争论乐趣时崩溃

时间:2010-11-23 09:04:28

标签: ios iphone uibutton selector

for (int i=0;i<[tableDataSource count];i++) 
{
        NSDictionary *dict = [tableDataSource objectAtIndex:i];
        rowText = [dict objectForKey:@"title"];

        UIButton *btn = [UIButton buttonWithType: UIButtonTypeRoundedRect];
        [btn setTitle:rowText forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(myActionbtnText:) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(60,  40+2*(40*i), 200, 40);
        btn.alpha = 0.81;

        [self.view addSubview:btn];
}

我将动作分配给动态按钮时出错我的动作如下所示,当按钮事件发生时如何传递对象/参数。

-(void) myAction:(NSString *)btnText; 
{
    NSLog(@"%@ Button Clicked",btnText);
}

2 个答案:

答案 0 :(得分:1)

试试这个:

for (int i=0;i<[tableDataSource count];i++)
{
    UIButton *btn = [UIButton buttonWithType: UIButtonTypeRoundedRect];
    [btn setTitle:rowText forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(myActionbtnText:) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = i;
    btn.frame = CGRectMake(60,  40+2*(40*i), 200, 40);
    btn.alpha = 0.81;

    [self.view addSubview:btn];
}

-(void) myAction:(UIButton*)sender {
    NSDictionnary *dict = [tableDataSource objectAtIndex:sender.tag];
    NSString* rowText = (NSString*)[dict objectForKey:@"title"];
    NSLog(@"%@ Button Clicked",rowText);
}

答案 1 :(得分:1)

您的解决方案有几个问题。

  1. UIButton不回复addTarget:action:withObject:forControlEvents:,而是addTarget:action:forControlEvents。这就是您的应用程序崩溃的原因。
  2. 选择器应为@selector(myAction:)。不应包含该参数。
  3. 我很确定它无论如何都不会起作用,因为按下按钮rowText将超出范围并且不再可用。这就是你应该使用@MathieuF解决方案的原因(只需确保正确指定选择器)。