Search code examples
iosios5ios6uibuttonsender

Check which UIButton was Clicked from another function


In my xib I have taken 4 UIbuttons named button 1, 2, 3 and 4. These four buttons are connected two four different IBAction methods which perform different functions.

Now I have one more button called "Save" This has also a different IBAction method.

- (IBAction)Save:(id)sender
{

}

Now here I want to check which of the above 4 UIButtons have been clicked.

For this I tried checking this way

- (IBAction)Save:(id)sender
{
   if(sender == button1)
   {
      //Do this
   }
   else if (sender == button2)
   {
       //Do this
   }

}

But this is not working. I am doing something wrong.Please help me out

Regards Ranjit.


Solution

  • You can set the tag values for each button in the interface builder and set actions of all buttons to this method

    //set global variable flag.

       int flag;
    
    - (IBAction)buttonClicked:(id)sender
    {
    
    switch ([sender tag])
    {
        case 0:
             {
                  flag =0;
                 // implement action for first button
    
             }
            break;
        case 1:
            {
                  flag =1;
                // implement action for second button
    
            }
            break;
        case 2:
            {
                  flag =2;
                // implement action for third button
    
            }
            break;
            //so on
        default:
            break;
    }
    }
    

    for save button

    - (IBAction)save:(id)sender
    {
    
    switch (flag)
    {
        case 0:
             {
    
                 //  first button clicked
    
             }
            break;
        case 1:
            { 
                //  second button clicked
    
            }
            break;
        case 2:
            {
                //  third button clicked
    
            }
            break;
            //so on
        default:
            break;
    }
    }