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);
}
答案 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)
您的解决方案有几个问题。
addTarget:action:withObject:forControlEvents:
,而是addTarget:action:forControlEvents
。这就是您的应用程序崩溃的原因。@selector(myAction:)
。不应包含该参数。rowText
将超出范围并且不再可用。这就是你应该使用@MathieuF解决方案的原因(只需确保正确指定选择器)。