Lloyd
Lloyd

Reputation: 351

Hiding multiple buttons with one button click Objective C

I am trying to hide two buttons when I press one button on the ViewController. I can only seem to hide the button I click but using [sender setHidden:YES];. The buttons I have:

- (IBAction)Button1:(UIButton*)sender;

- (IBAction)Button2:(UIButton*)sender;

I can't seem to use Button2.hidden = YES in Button1. Is there a way round this?

Upvotes: 0

Views: 1082

Answers (2)

Andrew Romanov
Andrew Romanov

Reputation: 5076

You should create button property in your viewController, and use it to hide button:

@interface ViewController ()

  @property (nonatomic, strong) IBOutlet UIButton* button1;
  @property (nonatomic, strong) IBOutlet UIButton* button2;

- (IBAction)action1:(id)sender;
- (IBAction)action2:(id)sender;

@end

In the actions:

- (void)setButtonsHidden:(BOOL)hidden
{
   _button1.hidden = hidden;
   _button2.hidden = hidden;
}

#pragma mark Actions
- (IBAction)action1:(id)sender
{
    [self setButtonsHidden:YES];
}

- (IBAction)action2:(id)sender
{
   [self setButtonsHidden:YES];
}

Also you can use NSArray to store all buttons references:

@interface ViewController ()

   @property (nonatomic, strong) IBOutletCollection(UIButton) NSArray* allButtons;
   <.....>

In setButtonsHidden: method:

- (void)setButtonsHidden:(BOOL)hidden
{
    [_allButtons enumerateObjectsUsingBlock:^(UIButton* obj, NSUInteger idx, BOOL *stop) {
    obj.hidden = hidden;
    }];
 }

Upvotes: 2

H.P.
H.P.

Reputation: 113

Viewcontroller.h

@property (weak, nonatomic) IBOutlet UIButton *button1;
@property (weak, nonatomic) IBOutlet UIButton *button2;
- (IBAction)button1:(UIButton *)sender;
- (IBAction)button2:(UIButton *)sender;

Viewcontroller.m

- (IBAction)button1:(UIButton *)sender
{
    _button1.hidden = YES;
    _button2.hidden = YES;
}

- (IBAction)button2:(UIButton *)sender
{
    _button1.hidden = YES;
    _button2.hidden = YES;
}

Upvotes: 1

Related Questions