问题
I have a method with multiple variables:
-(void) showImg:(UIBarButtonItem *)sender string1:(NSString *) string2:(NSString *);
I want to send NSString
values (As this function
is used for multiple elements).
This is how I add my action
when no parameters are needed:
[myButton addTarget:self action:@selector(showImg) forControlEvents: UIControlEventTouchUpInside];
I tried adding parameters within the @selector
like this:
[myButton performSelector @selector(showImg:string1:string2::) withObject:@"-1" withObject:@"-1"];
But this does not work. How may I call my function
with multiple parameters directly inside the @selector
?
回答1:
You can make your UIButton
call a function
in between (like a middle man), to control the next functions parameters.
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
}
回答2:
The following line is wrong :
[myButton performSelector @selector(showImg:string1:string2::) withObject:@"-1" withObject:@"-1"];
You can't pass parameters like this to the selector, that's why you have an error. I don't think you can pass multiple parameters to a selector. Maybe you can try to set a tag to your button with your const value (works with integers)
For example :
//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;
}
Just a suggestion.. :)
来源:https://stackoverflow.com/questions/12763733/perfomselector-on-button-and-sending-parameters