call a method with a param when pressing a button

Discussion in 'iOS Programming' started by pier, Jun 25, 2011.

  1. pier macrumors 6502

    pier

    Joined:
    Feb 7, 2009
    #1
    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
     
  2. Sykte macrumors regular

    Joined:
    Aug 26, 2010
    #2

    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.
     
  3. pier thread starter macrumors 6502

    pier

    Joined:
    Feb 7, 2009
    #3
    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.
     
  4. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    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;
    }
    }
    
     

Share This Page