Jacksonkr
Jacksonkr

Reputation: 32247

ios multiple UIButtons to use one handler (via IB)

Is there a way to have all UIButtons on a view use the same Touch Up Inside handler? Or perhaps set all the buttons to the same delegate using the Interface Builder?

Upvotes: 2

Views: 2209

Answers (4)

Jeff Wolski
Jeff Wolski

Reputation: 6372

Yes. Control drag the first button into the header file the way your normally would and create the action. Then in the .xib file, connect each of the other buttons to File's Owner and choose the same action that you just created.

In the .xib file, look at the Attributes Inspector on the View pane. You can set the Tag for each button individually. Then you can use the following code...

- (IBAction)myButtons:(id)sender {

    switch ([(UIButton *)sender tag]) {
        case 0:
            // code for first button
            break;

        case 1:
            // code for second button
            break;

        case 2:
            // code for third button
            break;

        default:
            break;
    }
}

Upvotes: 4

matt
matt

Reputation: 535557

Certainly, why not? Just control-drag from each button to the same IBAction method in your code. However, that method will then have to consist of a massive if statement to determine which button it is and what it should do in response, since you surely don't want all those buttons to do the same thing.

Upvotes: 1

bryanmac
bryanmac

Reputation: 39306

There's no problem with making the same IBAction as the target/action from multiple buttons. Just bind up multiple ones in IB

The programatic equivalent is:

[button1 addTarget:self action:@selector(oneAction:) forControlEvents:UIControlEventTouchUpInside];

[button2 addTarget:self action:@selector(oneAction:) forControlEvents:UIControlEventTouchUpInside];

Upvotes: 2

Sanjay Chaudhry
Sanjay Chaudhry

Reputation: 3181

Yes, you can attach same IBAction to as many button events as you like. The actual button that initiated the action will be passed as an argument to the IBAction, and you can differente it there (if you need to).

Upvotes: 2

Related Questions