views:

121

answers:

4

I have the following method

-(IBAction)back:(id)sender {

}

and would like to be able to know the sender id.

e.g. if there are multiple buttons linked to this method, I would like to know which button was pressed.

A: 

Set the tag property of each button to a unique integer (either in IB or programmatically) and switch on it inside your action method.

warrenm
thanks, how do I switch it on?
@user397363: He said "switch *on it*", meaning check the tag and do different things depending on what it is.
Chuck
ah sh#t. tired.
+5  A: 

Simply use the tag property, inherited from UIView, which is a NSInteger, in a switch statement, or using if conditions.

The tag property can be set in your code, or through InterfaceBuilder.

Macmade
+2  A: 

[sender tag]

I don't know what you mean by "id" (the "sender" is an id, effectively an NSObject *), but you could use tags. You have to set the tag beforehand in Interface Builder or programmatically.

Bored Astronaut
cool, thanks. exact answer.
+2  A: 

If you have set up IBOutlets for the buttons in your interface then you can simply compare the sender to those.

That is in your interface definition if you have

...
  (IBOutlet) UIButton *button1;
  (IBOutlet) UIButton *button2;
...

and in your implementation you have:

- (IBAction) buttonPressed: (id) sender
{
  if (sender == button1) {
    ....
  }
  else if (sender == button2) {
    ...
  }
}

Personally, I'd prefer to use different action methods for each button and then they can all call a common routine for the things that are common. However, for simple projects the above will work.

-J

Jeremy