peterbonar
peterbonar

Reputation: 599

Disable a button on a timer iOS

I am making a timer app on XCode 7 using Objective-C and I would like to disable the button that is connected to the action startCount while the following code is being executed

- (IBAction)startCount:(id)sender {

countInt = 0;
self.Label.text = [NSString stringWithFormat:@"%i", countInt];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countTimer) userInfo:nil repeats:YES];
}

What line of code would I need to add to this to disable the button connected to the action startCount?

Thanks

Upvotes: 1

Views: 377

Answers (2)

luk2302
luk2302

Reputation: 57114

You need to disable the sender via the enabled flag:

((UIButton*)sender).enabled = false;

Don't forget to re-enable the button after the timer finishes.

If the enabled state is NO, the control ignores touch events [...]

Alternatively to the cast I made in the above code: Change your method signature to take in a UIButton*, not just an id, that way you can make sure the cast will not fail. A slight variation of the cast would be to cast to UIControl* instead.

Upvotes: 1

TwoStraws
TwoStraws

Reputation: 13127

If I understand you correctly: to make your code easier to understand (and to avoid unpleasant race conditions if there are multiple buttons that might be tapped/disabled), I would suggest avoiding using a timer. Instead, consider dispatch_after() like this:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    sender.userInteractionEnabled = false;
});

We get sender being passed into the method, and it will be the button that was tapped. 1 * NSEC_PER_SEC means "delay for one second."

Upvotes: 0

Related Questions