Wilhelm Michaelsen
Wilhelm Michaelsen

Reputation: 663

make button toggle method — objective-c

I have 4 buttons. When they are taped they each create a UIView underneath it, they expand under the buttons. I want the view to go back to its original when the buttons are taped a second time. How is this done?

Upvotes: 0

Views: 976

Answers (4)

danypata
danypata

Reputation: 10175

You can use the selected property of your button, something like:

-(void)yourButtonIsTapped:(UIButton*)button {
   if(button.selected) { //first time
       //expand the view
      button.selected = NO;
   }
   else { // second time
      //hide view
      button.selected = YES;
   }
}

You can link the buttons from the IB th this method for the touchUpInside event but you will have to change the return type from void to IBAction.

And I think there are several other solutions for this case but this is the faster one and the easiest to explain.

Upvotes: 1

Marco Pace
Marco Pace

Reputation: 3870

Set every tag button to 0, change it to the opposite value when you press the button. Here is what you'll get:

  1. First time that you press the button: button's tag = 0, expand the view and turn it to 1.
  2. Second time you press the button: button's tag = 1, collapse it and turn it to 0.

So you haven't to create a bool for every button but you can use your button's tag variable. Code should be like this.

- (void)handleButton:(UIButton *)button{
    if(button.tag == 0) { <expandButton> }
    else                { <collapseButton> }

    button.tag = !button.tag;
}

Upvotes: 0

savner
savner

Reputation: 840

Set an instance BOOL and flip it accordingly. In the IBAction the button is tied to check the BOOL and call the appropriate method to adjust the view.

Upvotes: 1

DrummerB
DrummerB

Reputation: 40211

You can remove a view simply by calling

[viewUnderButton removeFromSuperview];

Upvotes: 0

Related Questions