2012-10-06 34 views
-1

我有多個變量的方法:perfomSelector上按鈕和發送參數

-(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"]; 

但是,這是行不通的。如何在@selector內直接呼叫我的function多個參數?

回答

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 
} 
+0

它聽起來不錯,如果我想從其他方法調用'showImg'沒有按鈕引用,我可以使用不可用的'nil'來代替'(id)發送器嗎? – vadim

+0

是的,你可以刪除參數,並使用@選擇器(showImg)和 - (void)showImg – D25

+0

你發佈的代碼對我來說是完美的,我所要求的是如果我想調用該方法作爲書面,但我沒有按鈕發送給發件人,只是想從其他地方調用它而不改變它,我可以做這樣的事情嗎?[self showImg:nil string1:@「32.5645」string2:@「32.35553」]; ' – vadim

0

下面一行是錯誤的:

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

你不能像這樣的參數傳遞到選擇,這就是爲什麼你有一個錯誤。我不認爲你可以傳遞多個參數給選擇器。也許你可以嘗試設置標籤,就可以扣你的常量的值(與整數作品)

例如:

//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; 
} 

只是一個建議.. :)