Alex Rivera | Logout

Pass different parameters to an IBAction

Asked 2010-01-22T12:23:19.213
14

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".

Edit
Report

3 Answers

1

Give your various UIButton instances different tag property values.

In your IBAction method -myMethod:, you might then do something like:

- (void) myMethod:(id)sender {
    switch (sender.tag) {
        case (firstButtonTag):
           doFooStuff;
           break;
        case (secondButtonTag):
           doBarStuff;
           break;
        // etc.
    }
}

The values firstButtonTag and secondButtonTag can be stored in an enum if you want to make this easy to maintain.

answered 2010-01-22T12:27:43.893
1

You can't pass parameters through an IBAction. What I usually do is give the buttons the unique tag in IB. THe tag is an integer value so I u then use a simple lookup table to convert the tag to some value.

In this case, three buttons but tags 1 to 3:

- (IBAction) buttonPressed: (UIButton*) sender
{
    static const NSString* names = { @"Foo", @"Bar", @"Baz" };
    id tag = [sender tag];
    if (tag >= 1 && tag <= 3) {
        NSLog(@"Button pressed is %@", names[tag]);
    }
}
answered 2010-01-22T12:27:58.063
-1

You don't. The only parameter is the sender object, which you may use to have a different behavior, but what I'd do is define 2 action methods, which simply in turn call the same method with a different parameter, i.e. you'd have:

- (IBAction)button1:(id)sender
{
    [self doStuff:kButton1];
}

- (IBAction)button2:(id)sender
{
    [self doStuff:kButton2];
}

- (void)doStuff:(ParamType)param;
{
    ...
}

In defense of that method (no pun intended), I'd add that it makes clearer when you review your UI with Interface Builder to see that different buttons actually have different effects, which is harder to tell if they all call whateverAction:

answered 2010-01-22T12:28:53.443

Your Answer