perfomSelector on按钮和发送参数

时间:2012-10-06 20:46:46

标签: iphone objective-c selector

我有一个包含多个变量的方法:

-(void) showImg:(UIBarButtonItem *)sender string1:(NSString *) string2:(NSString *);

我想发送NSString个值(因为此function用于多个元素)。

这是我在不需要参数时添加action的方式:

[myButton addTarget:self action:@selector(showImg) forControlEvents: UIControlEventTouchUpInside];

我尝试在@selector中添加参数,如下所示:

[myButton performSelector @selector(showImg:string1:string2::) withObject:@"-1" withObject:@"-1"];

但这不起作用。如何直接在function

中调用我的@selector多个参数

2 个答案:

答案 0 :(得分:4)

您可以让UIButton之间的呼叫为function(如中间人),以控制下一个功能参数。

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

-(void) buttonTapped:(id)sender{
    if(<some logical condition>){
        [self showImg:sender string1:@"-1" string2:@"-1"];
    }else {
        [self showImg:sender string1:@"otherVal1" string2:@"otherVal2"];
    }
}

-(void) showImg:(id)sender string1:(NSString *)string1 string2:(NSString*)string2 {
    //Other logic
}

答案 1 :(得分:0)

以下行错误:

[myButton performSelector @selector(showImg:string1:string2::) withObject:@"-1" withObject:@"-1"];

你不能将这样的参数传递给选择器,这就是你有错误的原因。我认为你不能将多个参数传递给选择器。也许您可以尝试使用const值(使用整数)为您的按钮设置标记

例如:

//Init your button......
[myButton setTag:1];
[myButton addTarget:self action:@selector(showImg:) forControlEvents: UIControlEventTouchUpInside];

- (void)showImg:(id)sender {
  UIButton *btn = (UIButton *)sender;
  int value = btn.tag;
}

只是一个建议.. :))