Search code examples
objective-cios6uibutton

Programmatically change the state of a UIButton


I've got a pop-up view that loads when a user clicks on a TableView with Core Data elements. On the pop-up view I have a label that represents an int value.

The pop-up view has two butons, one for decreasing the value of the label by 1 and one for increasing it by one. So + and -

What I want to do is to disable the minus button if the label's value is 0. What I've tried is:

-(void)viewDidLayoutSubviews{
     NSString *daString = currentVal.text;
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        [f setNumberStyle:NSNumberFormatterDecimalStyle];
        NSNumber * myNumber = [f numberFromString:daString];
        int number = [myNumber intValue];
        if (number==0)
            minus.enabled = NO;
        else
            minus.enabled = YES
}

The problem with my code is that the button stays disabled after I increase the label's value, and it's no longer equal to 0. Any suggestions?


Solution

  • You should keep a reference to minus button e.g.

    @property (strong, nonatomic) IBOutlet UIButton *minusButton;
    

    Set it with a value of your minus button, or connect outlet in Interface Builder

    in your action handler for plusButton, do something like that

    -(IBAction)plusAction:(id)sender {
         //Do your business logic
         ...
         self.minusButton.enabled = YES;
    }
    //In your minusButton action handler
    -(IBAction)minusAction:(id)sender {
         //Do your business logic
         ...
         NSString *daString = currentVal.text;
         NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
         [f setNumberStyle:NSNumberFormatterDecimalStyle];
         NSNumber * myNumber = [f numberFromString:daString];
         int number = [myNumber intValue];
         if (number==0)
            self.minusButton.enabled = NO;
         else
            self.minusButton.enabled = YES
    }