Question

I want to re-enable a UIButton in Xcode after it has been disabled. I disabled the button by calling the IBAction when the button is pressed.

- (IBAction)A0:(UIButton *)sender{
UIButton *enableButton = (UIButton *)sender;
enableButton.enabled = NO;
}

- (IBAction)B0:(UIButton *)sender{
UIButton *enableButton = (UIButton *)sender;
enableButton.enabled = NO;
}

// Lots more buttons

-(Void) reset {

//re-enable all buttons

}

I wish to be able to re-enable all the buttons when the reset method is called

Thanks

Was it helpful?

Solution

If you need to manipulate user interface objects like buttons, create IBOutlet properties in the view controller that manages the objects and link the objects to those properties. That done, you'll be able to use the properties to enable the button(s) like this:

-(void) reset {
    //re-enable all buttons
    self.buttonA.enabled = YES;
    self.buttonB.enabled = YES;
    //...and so on
}

If you don't want to use outlets for some reason (e.g. you have a large number of buttons and don't often need a reference to each individual button), you might also consider using tags. Every view has an integer tag property which you can set to any value you like. Tags can be set in the .xib/storyboard editor. Once you've set a view's tag, you can easily find it in your view hierarchy using the -viewWithTag: method. If you use tags, your -reset method would look something like:

-(void) reset {
    //re-enable all buttons
    [[self.view viewWithTag:kTagForButtonA] setEnabled:YES];
    [[self.view viewWithTag:kTagForButtonB] setEnabled:YES];
    //...and so on
}

where kTagForButtonA and kTagForButtonB are integer constants that match the tags set on individual buttons. If you have lots of buttons with consecutive tags, you could obviously also use a for loop to set each one in turn.

Also, it looks like all your actions do exactly the same thing -- each one disables the button that sent the message. If that's the case, you can use a single action for all your buttons:

- (IBAction)buttonAction:(UIButton *)sender {
    sender.enabled = NO;
}

OTHER TIPS

If you have many UIButton objects and it's not feasible to manually enable each UIButton object by name, you can try this:

-(void)reset
{
    for(UIView *currentView in [self.view subviews]) {
        if ([currentView  isKindOfClass:[UIButton class]]) {
            [currentView setEnabled:YES];
        }
    }
}

this will get all UIButton objects you have in self.view and setEnabled:YES to them (whether they're already enabled or not)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top