Disable a button based on a label's value
I have a UILabel
cal开发者_如何转开发led label
, and you can add or subtract 1 from it using two buttons. When you subtract all the way down to 0, I want the minus button to stop working. And if the value is added, I want the minus button to work again. Here is the method/code I'm using for the add/subtract button:
- (IBAction)addButton1:(id)sender {
[label setText:[NSString stringWithFormat:@"%d",[label.text intValue] +1]];
}
the code is the same for both the add/subtract methods. Except the +1 at the end is a -1.
I tried:
- (IBAction)addButton1:(id)sender {
int val = [label.text intValue];
[label setText:[NSString stringWithFormat:@"%d",[label.text intValue] +1]];
if(val - 1 <= 0) {
UIButton *button = (UIButton *)sender;
[button setEnabled:NO];
}
}
Try
- (IBAction)addButton:(id)sender {
if ( [[label text] intValue] == 0)
[minusButton setEnabled:YES];
[label setText:[NSString stringWithFormat:@"%d",[label.text intValue] +1]];
}
- (IBAction)subButton:(id)sender {
[label setText:[NSString stringWithFormat:@"%d",[label.text intValue] -1]];
if ( [[label text] intValue] == 0)
[minusButton setEnabled:NO];
}
You simply need to keep the pointer to the minus button (simply create an IBOutlet
and then link it to the button using IB)
精彩评论