Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

pier

macrumors 6502a
Original poster
Feb 7, 2009
584
986
So I'm creating my first iOS app!!!

I want to create a calculator. Nothing fancy, just to start with something simple.

I have my buttons, and I know how to call a method when the button is pressed.

but how can I call a method with a parameter when the button is pressed?

My method would be something like this:

Code:
- (IBAction) writeNumber: (int) number {
....
}

TIA
 
So I'm creating my first iOS app!!!

I want to create a calculator. Nothing fancy, just to start with something simple.

I have my buttons, and I know how to call a method when the button is pressed.

but how can I call a method with a parameter when the button is pressed?

My method would be something like this:

Code:
- (IBAction) writeNumber: (int) number {
....
}

TIA


Better question is how would the button understand or know to pass this number? The button will not and does not own the data, it's purpose is only to take action.

Code:
-(IBAction)numberOnePressed:(id)sender {
//take action here as number one
}

-(IBAction)numberTwoPressed:(id)sender {
//take action here as number two
}

Now you could easily do this with one method but that would require a better understanding. When you get a moment look over the MVC pattern.
 
If it's not possible to call the event handler with a parameter (other than the IBAction), I presume it should be possible to know which button generated the event, and act accordingly.
 
The event handler does take a parameter: a pointer to the button that sent the message.

So if we assume you have IBOutlet variables pointing to each of the buttons you can do

Code:
-(IBAction) numberPressed:(id) sender
{
if (sender == no1Button)
{
}
else if (sender ==no2Button)
{
}
}

The other option is to set the tag property of the buttons and use that:

Code:
-(IBAction) numberPressed:(id) sender
{
int tag = [sender tag];
switch (tag)
{
case 1:
// do something
break;
case 2;
// do something else
break;
}
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.