3

I have multiple UIButtons in my app. I also use interfacebuilder. In my .h i have something like this

  IBOutlet UIButton *button1;
    IBOutlet UIButton *button2;
    IBOutlet UIButton *button3;
    - (IBAction)buttonPressed;

Then In my m i want to do something like this

- (IBAction)buttonPressed {


if (theButtonIpressed == button1) 

{

// do something if 

}

}

The problem is I don't have something called "theButtonIpressed" so I cant do this. What should my if statement look like? I don't want to make a -(IBAction) for each button. Is there something that I can determine which button was pressed? Thanks!

Thanks,

-David

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
bobbypage
  • 2,157
  • 2
  • 21
  • 21

4 Answers4

4

You can also set the tag property for each button in the interface builder and then use it to find out which button was pressed.... This also means that you don't need to define all your button references (UIButton) and keep track of them in code....

- (void) doSomething:(id)sender {

    int buttonPressed = [sender tag];

    switch (buttonPressed) {
       case 0:....
       // etc
     }
}
Eric Schweichler
  • 1,092
  • 6
  • 11
2

Define your - (IBAction)buttonPressed to:

- (IBAction)buttonPressed: (UIButton *) buttonIpressed

Then it will work.

Alfons
  • 1,845
  • 14
  • 16
1

- (IBAction)buttonPressed:(UIButton*)button

But if you're doing something different for each button then the proper way to do it is to create separate IBActions.

indragie
  • 18,002
  • 16
  • 95
  • 164
0

You can use tag values for each buttons

 IBOutlet UIButton *button1;
 button1.tag = 100;
 IBOutlet UIButton *button2; 
 button2.tag = 200;
 IBOutlet UIButton *button3;
 button3.tag = 300;

 - (IBAction)buttonPressed:(id)sender
{
   if ([sender tag]==100) 
   {
     NSLOG("button1");
   }
   else if([sender tag]==200)
   {
     NSLOG("button2");
   }
   else {
     NSLOG("button3");
   }

}
IOS Rocks
  • 2,127
  • 2
  • 21
  • 24