Matt S
Matt S

Reputation: 185

Check to see if UIButton was pushed

I have four UI buttons and I want different things to happen based on which button the user pushes. I've tried using a boolean to check if a button is pressed, but it doesn't seem to be working. The boolean code for each button is basically:

 -(IBAction)FirstChoice:(id)sender
{
 wasClicked = YES;
}

then in the main function itself:

if(wasClicked)
{
    returnView.text = @"Test";
}

however when I push any of the buttons, the test text doesn't appear.

Upvotes: 0

Views: 184

Answers (2)

Vizllx
Vizllx

Reputation: 9246

I think you should use a common "Touch up inside "outlet function for all buttons... and Set different tags for each buttons.. for example

-(IBAction)FirstChoice:(id)sender // common "Touch up inside" action for all four buttons
{
 UIButton *btn=(UIButton *)sender; //assuming that you have set tag for buttons

      if(btn.tag==94)
        {
          //Do any thing for button 1
         }
       else if (btn.tag==93)
        {
          returnView.text = @"Test";
          //Do any thing for button 2
         }
       else if (btn.tag==92)
        {
          //Do any thing for button 3
         }
        else
           {
             //Do any thing for button 4

            }


}

Upvotes: 1

Alejandro Iván
Alejandro Iván

Reputation: 4061

This is basically the same approach as Vizllx answer, but a little bit clear. This assumes you have already set tags for every button that will invoke your IBAction. As this method will be invoked from UIButtons, I changed the type of the argument. If you need it to be called from another kind of objects, change it to id and do the manual casting.

- (IBAction)FirstChoide:(UIButton *)sender
{
    const int BUTTON_TAG_1 = 92; // Identifier (tag) from a button
    const int BUTTON_TAG_2 = 93; // Another one
    // ...


    int tag = sender.tag; // tag returns an NSInteger, so it casts automatically to an int

    switch(tag)
    {
        case BUTTON_TAG_1:
            // Do stuff like setting strings to another elements, for example:
            // returnView.text = @"Test";
            break;

        case BUTTON_TAG_2:
            // Again...
            break;

        default:
            // Any other cases...
    }
}

Upvotes: 0

Related Questions