Pass different parameters to an IBAction

ahmed picture ahmed · Jan 22, 2010 · Viewed 18.8k times · Source

My iPhone app has many buttons and I want all the buttons to call the same method, but with different parameters.

For example I want tapping one button to call the method myMethod: with the argument @"foo", and a second button should call the same method but with argument @"bar".

Answer

kennytm picture kennytm · Jan 22, 2010

The so called "IBActions" must have one of these signatures:

-(void)action;
-(void)actionWithSender:(id)sender;
-(void)actionWithSender:(id)sender event:(UIEvent*)event;

You cannot add any other parameters. Nevertheless you can use sender (which is button1 or button2 in your case) to get the parameter:

-(void)actionWithSender:(UIButton*)sender {
   NSString* parameter;
   if (sender.tag == 1)   // button1
     parameter = @"foo";
   else                   // button2
     parameter = @"bar";
   ...
}